我有以下配置文件:
@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;
}
}
Run Code Online (Sandbox Code Playgroud)
我使用以下VM选项运行我的应用程序:
-Dproperty=propertyValue
Run Code Online (Sandbox Code Playgroud)
所以我希望我的应用程序在启动时加载特定的属性文件.但由于某些原因,在此阶段@Value注释不会被处理,属性也是如此null.另一方面,如果我PropertyPlaceholderConfigurer通过xml文件配置 - 一切都按预期完美.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>
Run Code Online (Sandbox Code Playgroud)
如果我尝试在另一个Spring配置文件中注入属性值 - 它被正确注入.如果我将PropertyPlaceholderConfigurerbean创建移动到该配置文件 - 字段值再次为null.
作为解决方法,我使用这行代码:
System.getProperties().getProperty("property", "defaultValue")
Run Code Online (Sandbox Code Playgroud)
哪个也有效,但我想知道为什么会发生这种行为,也许有可能以其他方式重写它但没有xml?