目前我有一个加载属性文件的Spring xml配置(Spring 4)。Spring占位符不能解析JavaConfig中的属性
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' – superbob 2015-03-19 09:49:13
'my.app.service'属性解决好吗?使用@Value(“$ {my.app.service}”)检查,如果问题来自属性嵌套,我会漫步。 – superbob 2015-03-19 09:53:00