[英]How to use environment variables with properties file in Spring context file
I am trying to read in a configuration file based on a system environment variable. 我试图基于系统环境变量读取配置文件。 My environment variable is FOO_ENV
with value dev
and dev.properties
contains the properties bar.host
and bar.port
. 我的环境变量是FOO_ENV
,其值为dev
, dev.properties
包含属性bar.host
和bar.port
。
<context:property-placeholder />
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="classpath:${FOO_ENV}.properties"></property>
<property name="ignoreUnresolvablePlaceholders" value="true" />
</bean>
<bean id="myServer" class="org.apache.solr.client.solrj.impl.HttpSolrServer">
<property name="ignoreUnresolvablePlaceholders" value="true" />
<constructor-arg type="String" value="http://${my.host}:${my.port}/" />
</bean>
When I deploy this in tomcat, I get the following error: 当我在tomcat中部署它时,我收到以下错误:
11:48:39.324 [localhost-startStop-14] ERROR o.s.web.context.ContextLoader - Context initialization failed
org.springframework.beans.factory.BeanDefinitionStoreException: Invalid bean definition with name 'myServer' defined in ServletContext resource [/WEB-INF/my-context.xml]:
Could not resolve placeholder 'my.host' in string value [http://${my.host}:${my.port}]
at org.springframework.beans.factory.config.PlaceholderConfigurerSupport.doProcessProperties(PlaceholderConfigurerSupport.java:209) ~[spring-beans-3.1.2.RELEASE.jar:3.1.2.RELEASE]
By replacing $FOO_ENV
with dev
in the context file, I have determined that the properties file can be read correctly. 通过在上下文文件中用dev
替换$FOO_ENV
,我确定可以正确读取属性文件。 By changing FOO_ENV
to other names, I can show that Spring is reading the environment variable. 通过将FOO_ENV
更改为其他名称,我可以证明Spring正在读取环境变量。
It seems that the element 看来这个元素
<property name="ignoreUnresolvablePlaceholders" value="true" />
should allow Spring to ignore that ${my.host}
is not an environment variable, but though I've tried it in various places, I still get the same error, which indicates that my.host
is not found. 应该允许Spring忽略${my.host}
不是环境变量,但是虽然我已经在各个地方尝试过,但我仍然得到相同的错误,这表明my.host
。
You actually have two PropertyPlaceHolderConfigurers defined here. 实际上你在这里定义了两个PropertyPlaceHolderConfigurers。 One via the context namespace and one explicitly. 一个通过上下文命名空间和一个显式。 Spring is probably picking the one created via the context namespace. Spring可能会选择通过上下文命名空间创建的那个。 You could either set 'ignore-unresolvable' on the context tag and remove your propertyConfigurer bean like so: 您可以在上下文标记上设置'ignore-unresolvable'并删除propertyConfigurer bean,如下所示:
<context:property-placeholder ignore-unresolvable="true"/>
Or if you need more control over PropertyPlaceHolderConfigurer go the other way and remove the context:property-placeholder tag. 或者,如果您需要对PropertyPlaceHolderConfigurer进行更多控制,请转到另一种方式并删除context:property-placeholder标记。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.