java Spring如何用环境变量替换${}?
这是我的XML bean配置
<beans:bean class="com.utils.OverridingPropertySourcesPlaceholderConfigurer">
<beans:property name="overridingSource" value="file:${config_path}/config.properties"/>
<beans:property name="locations" value="classpath*:META-INF/*-config.properties" />
</beans:bean>
下面是我的OverridingPropertySourcesplaceConfigurer
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
public class OverridingPropertySourcesPlaceholderConfigurer extends PropertySourcesPlaceholderConfigurer implements InitializingBean, ApplicationContextAware {
protected ApplicationContext applicationContext;
protected Resource overridingSource;
public void setOverridingSource(Resource overridingSource) {
this.overridingSource = overridingSource;
}
.......
这是我的tomcat上下文,它在环境变量下注入值为C:/myFolder
的config_path
强>
<Environment name="config_path" override="false" type="java.lang.String" value="C:/myFolder"></Environment>
当我启动服务器时,我看到在OverridingPropertySourcesPlaceholderConfigurer
下调用了setOverridingSource()
方法,并解析了overridingSource属性
改为C:/myFolder
而不是config_path
。我不确定spring是如何用通过web服务器设置的环境值中的实际值替换占位符config_path
的
我知道BeanFactoryProcessor可以为其他SpringBean做这件事。但我怀疑{
我正在使用spring 4.2
# 1 楼答案
从Spring 3开始,如果设置了环境变量,它将在类
PropertySourcesPlaceholderConfigurer
下自动完成。见docs另见Can I use an Environment variable based location for Spring FileSystemResource?