【发布时间】:2016-01-25 12:02:52
【问题描述】:
我有以下配置文件:
@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 需要是static。 -
@M.Deinum
@PropertySource非常适合我,但是如果我有ProperySourcesPlaceholderConfigurer的自定义实现呢? -
为什么需要自定义实现。
-
@M.Deinum 例如从 ZooKeeper 加载属性
-
您不需要自定义实现,您需要自定义
PropertySource
标签: java xml spring configuration