我有以下的配置文件:春@Configuration文件不能解決@Value註釋
@Configuration
public class PropertyPlaceholderConfigurerConfig {
@Value("${property:defaultValue}")
private String property;
@Bean
public static PropertyPlaceholderConfigurer ppc() throws IOException {
PropertyPlaceholderConfigurer ppc = new PropertyPlaceholderConfigurer();
ppc.setLocations(new ClassPathResource("properties/" + property + ".properties"));
ppc.setIgnoreUnresolvablePlaceholders(true);
return ppc;
}
}
我有以下VM選項來運行我的應用程序:
-Dproperty=propertyValue
所以我就像我的應用程序在啓動時加載特定的屬性文件。但由於某種原因,在此階段@Value
註釋未處理,屬性爲null
。另一方面,如果我通過xml文件配置PropertyPlaceholderConfigurer
- 一切都按預期完美工作。 Xml文件示例:
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="ignoreResourceNotFound" value="true"/>
<property name="location">
<value>classpath:properties/${property:defaultValue}.properties</value>
</property>
</bean>
如果我嘗試在另一個Spring配置文件中注入屬性值 - 它被正確注入。如果我將我的PropertyPlaceholderConfigurer
bean創建移動到該配置文件 - 字段值再次爲空。
至於解決方法,我用這行代碼:
System.getProperties().getProperty("property", "defaultValue")
這也是工作,但我想知道爲什麼這樣的行爲發生,也許有可能改寫其他方式,但沒有XML?
首先,我強烈建議使用'ProperySourcesPlaceholderConfigurer'並在您的課堂上使用'@ PropertySource'。其次,這個bean需要是「靜態」的。 –
@ M.Deinum'@ PropertySource'對我來說非常完美,但是如果我有自定義的'ProperySourcesPlaceholderConfigurer'實現呢? –
爲什麼你需要一個自定義的實現。 –