环境变量未转换为系统属性

问题描述

在基于旧版Spring的应用程序(Spring 4.3)上工作时,我有一个奇怪的行为:Spring不能解析环境变量。 例如,我有一个环境变量:HOST_SERVICE_BASE_URL,当我在应用程序中使用${host.service.base.url}引用它时,该属性未解析,并且在启动过程中应用程序失败。

Caused by: java.lang.IllegalArgumentException: Could not resolve placeholder 'host.service.base.url' in value "${host.service.base.url}

我为属性解析定义了这些bean:

    @Bean
    public Propertiesfactorybean applicationProperties( ResourceLoader resourceLoader ) {
        Propertiesfactorybean propertiesFactory = new Propertiesfactorybean();
        propertiesFactory.setLocations( resourceLoader.getResource( "/WEB-INF/config/application.properties" ),resourceLoader.getResource( "/WEB-INF/config/application-dev.properties" ) );
        return propertiesFactory;
    }

    <bean id="dataConfigPropertyConfigurer"
          class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="ignoreResourceNotFound" value="true"/>
        <property name="searchSystemEnvironment" value="true"/>
        <property name="systemPropertiesModeName" value="SYstem_PROPERTIES_MODE_OVERRIDE"/>
        <property name="properties" ref="applicationProperties"/>
    </bean>

解决方法

您正在使用PropertyPlaceholderConfigurer(现已不推荐使用),尽管它可以查询系统环境,但它缺乏将那些属性映射为值的功能。即HOST_SERVICE_BASE_URL未映射为host.service.base.url

仅在使用SystemEnvironmentPropertySource时会自动注册并查阅的PropertySourcesPlaceholderConfigurer中提供该支持(从Spring 5.2开始推荐,但从3.1开始可用)。

<bean id="dataConfigPropertyConfigurer"
          class="org.springframework.context.support.PropertySourcesPlaceholderConfigurer">
    <property name="ignoreResourceNotFound" value="true"/>
    <property name="properties" ref="applicationProperties"/>
</bean>

或者用Java替换applicationProperties bean和XML部分。

@Bean
public static PropertySourcesPlaceholderConfigurer placeholderConfigurer() {
  PropertySourcesPlaceholderConfigurer configurer = new PropertySourcesPlaceholderConfigurer();
  configurer.setLocations({"/WEB-INF/config/application.properties",/WEB-INF/config/application-dev.properties"});
  configurer.setIgnoreResourceNotFound(true);
  return configurer;
}

或者,如果您真的坚持使用XML,请使用<context:property-placeholder />标签,它会自动执行此操作。

<context:property-placeholder properties="applicationProperties" ignore-resource-not-found="true" />

<context:property-placeholder locations="/WEB-INF/config/application.properties,/WEB-INF/config/application-dev.properties" ignore-resource-not-found="true" />

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...