有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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:/myFolderconfig_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做这件事。但我怀疑{}本身就是一个BeanFactoryProcessor。那么,谁在解决这个问题上的占位符价值呢

我正在使用spring 4.2


共 (1) 个答案

  1. # 1 楼答案

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

    Any local properties (e.g. those added via PropertiesLoaderSupport.setProperties(java.util.Properties), PropertiesLoaderSupport.setLocations(org.springframework.core.io.Resource...) et al.) are added as a PropertySource. Search precedence of local properties is based on the value of the localOverride property, which is by default false meaning that local properties are to be searched last, after all environment property sources.

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