[英]Spring placeholder doesn't resolve properties in JavaConfig
目前,我有一個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
但沒有獲得更多成功。
更新為使用configure PropertySourcesPlaceholderConfigurer
。 僅具有@PropertySource
批注是不夠的:
@Bean
public static PropertySourcesPlaceholderConfigurer properties() {
return new PropertySourcesPlaceholderConfigurer();
}
@PropertySource
批注不會自動向Spring注冊PropertySourcesPlaceholderConfigurer
。 因此,我們需要顯式配置PropertySourcesPlaceholderConfigurer
JIRA門票下方有更多有關此設計背后原理的信息:
https://jira.spring.io/browse/SPR-8539
更新:創建了簡單的Spring引導應用程序以使用嵌套屬性。 上面的配置可以正常工作。
https://github.com/mgooty/property-configurer/tree/master/complete
另一個選項是導入PropertyPlaceholderAutoConfiguration.class。
import org.springframework.boot.autoconfigure.PropertyPlaceholderAutoConfiguration;
@Import(PropertyPlaceholderAutoConfiguration.class)
如果注釋不存在,則在上下文中包含PropertySourcesPlaceholderConfigurer。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.