问题描述
在基于旧版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" />