Spring如何用环境变量替换$ {}?

时间:2018-03-30 03:23:34

标签: java spring spring-mvc dependency-injection spring-bean

这是我的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>

以下是我的OverridingPropertySourcesPlaceholderConfigurer

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上下文,它在环境变量下注入config_path,其值为C:/myFolder

<Environment name="config_path" override="false" type="java.lang.String" value="C:/myFolder"></Environment>

当我启动服务器时,我看到在setOverridingSource()下调用了OverridingPropertySourcesPlaceholderConfigurer方法并且解决了overridingSource属性 到C:/myFolder而不是config_path。我不确定spring是如何用来自通过Web服务器设置的环境值的实际值替换占位符config_path的?

我理解BeanFactoryProcessor可以为其他spring bean做这件事。但我怀疑的是OverridingPropertySourcesPlaceholderConfigurer extends PropertySourcesPlaceholderConfigurer本身就是一个BeanFactoryProcessor。那么谁在解决占位符价值呢?

我使用的是Spring 4.2

1 个答案:

答案 0 :(得分:0)

Spring 3以后,如果设置了环境变量,它将在类PropertySourcesPlaceholderConfigurer下自动完成。见docs

  

任何本地属性(例如通过   PropertiesLoaderSupport.setProperties(java.util.Properties)   PropertiesLoaderSupport.setLocations(org.springframework.core.io.Resource ...)   等人作为PropertySource添加。搜索本地优先级   属性基于localOverride属性的值,即   默认情况下为false意味着要搜索本地属性   最后,在所有环境财产来源之后。

另见Can I use an Environment variable based location for Spring FileSystemResource?