我有以下的配置文件:春@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'实现呢? –
为什么你需要一个自定义的实现。 –