【问题标题】:How Spring replacing the ${} with environment variable?Spring如何用环境变量替换${}?
【发布时间】:2018-09-09 02:43:29
【问题描述】:

这是我的 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 下被调用并且覆盖源属性被解析 到C:/myFolder 而不是config_path。我不确定 spring 如何将占位符 config_path 替换为通过 Web 服务器设置的环境值中的实际值?

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

我使用的是 spring 4.2

【问题讨论】:

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


    【解决方案1】:

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

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

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

    【讨论】:

      猜你喜欢
      • 2016-06-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-17
      • 2019-09-06
      • 1970-01-01
      • 1970-01-01
      • 2017-06-20
      相关资源
      最近更新 更多