Spring占位符不能解析JavaConfig中的属性
目前我有一个加载属性文件的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
。只要有@PropertySource
注释是不够的:
@Bean
public static PropertySourcesPlaceholderConfigurer properties() {
return new PropertySourcesPlaceholderConfigurer();
}
@PropertySource
注释不会自动注册和春天有个PropertySourcesPlaceholderConfigurer
。因此,我们需要明确配置PropertySourcesPlaceholderConfigurer
下面JIRA票对这种设计背后的基本原理的更多信息:
https://jira.spring.io/browse/SPR-8539
UPDATE: 创建简单的Spring启动应用程序使用嵌套的属性。它与上述配置工作正常。
https://github.com/mgooty/property-configurer/tree/master/complete
另一种方法是导入PropertyPlaceholderAutoConfiguration.class。
import org.springframework.boot.autoconfigure.PropertyPlaceholderAutoConfiguration;
@Import(PropertyPlaceholderAutoConfiguration.class)
注释在上下文中包含一个PropertySourcesPlaceholderConfigurer(如果它不存在)。
是的,这适用于基于** spring-boot **的上下文。 – 2016-10-31 11:18:04
即使它不能解决你的问题,我可以确认你应该使用'PropertySourcesPlaceholderConfigurer',而不是'PropertyPlaceholderConfigurer' – superbob 2015-03-19 09:49:13
'my.app.service'属性解决好吗?使用@Value(“$ {my.app.service}”)检查,如果问题来自属性嵌套,我会漫步。 – superbob 2015-03-19 09:53:00