【发布时间】:2015-05-22 08:14:17
【问题描述】:
目前我有一个加载属性文件的 Spring xml 配置(Spring 4)。
context.properties
my.app.service = myService
my.app.other = ${my.app.service}/sample
Spring xml配置
<bean id="contextProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<property name="ignoreResourceNotFound" value="true" />
<property name="fileEncoding" value="UTF-8" />
<property name="locations">
<list>
<value>classpath:context.properties</value>
</list>
</property>
</bean>
<bean id="placeholder" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="ignoreResourceNotFound" value="true" />
<property name="properties" ref="contextProperties" />
<property name="nullValue" value="@null" />
<property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE" />
</bean>
使用属性的Bean
@Component
public class MyComponent {
@Value("${my.app.other}")
private String others;
}
这很好用,others 的值是MyService/sample,例外。但是当我尝试用 JavaConfig 替换此配置时,我的组件中的 @Value 不会以相同的方式工作。该值不是myService/sample,而是${my.app.service}/sample。
@Configuration
@PropertySource(name="contextProperties", ignoreResourceNotFound=true, value={"classpath:context.properties"})
public class PropertiesConfiguration {
@Bean
public static PropertyPlaceholderConfigurer placeholder() throws IOException {
PropertyPlaceholderConfigurer placeholder = new PropertyPlaceholderConfigurer();
placeholder.setNullValue("@null");
placeholder.setSystemPropertiesMode(PropertyPlaceholderConfigurer.SYSTEM_PROPERTIES_MODE_OVERRIDE);
return placeholder;
}
}
我在从 xml 到 Javaconfig 的转换过程中遗漏了什么吗?
ps:我也尝试实例化 PropertySourcesPlaceholderConfigurer 而不是 PropertyPlaceholderConfigurer ,但没有取得更多成功。
【问题讨论】:
-
即使不能解决你的问题,我可以确认你应该使用
PropertySourcesPlaceholderConfigurer,而不是PropertyPlaceholderConfigurer -
my.app.service属性解析是否正常?检查@Value("${my.app.service}"),如果问题来自属性嵌套,我会徘徊。
标签: java spring properties-file spring-java-config