繁体   English   中英

如何在Spring上下文文件中使用具有属性文件的环境变量

[英]How to use environment variables with properties file in Spring context file

我试图基于系统环境变量读取配置文件。 我的环境变量是FOO_ENV ,其值为devdev.properties包含属性bar.hostbar.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>

当我在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]

通过在上下文文件中用dev替换$FOO_ENV ,我确定可以正确读取属性文件。 通过将FOO_ENV更改为其他名称,我可以证明Spring正在读取环境变量。

看来这个元素

<property name="ignoreUnresolvablePlaceholders" value="true" />

应该允许Spring忽略${my.host}不是环境变量,但是虽然我已经在各个地方尝试过,但我仍然得到相同的错误,这表明my.host

实际上你在这里定义了两个PropertyPlaceHolderConfigurers。 一个通过上下文命名空间和一个显式。 Spring可能会选择通过上下文命名空间创建的那个。 您可以在上下文标记上设置'ignore-unresolvable'并删除propertyConfigurer bean,如下所示:

<context:property-placeholder ignore-unresolvable="true"/>

或者,如果您需要对PropertyPlaceHolderConfigurer进行更多控制,请转到另一种方式并删除co​​ntext:property-placeholder标记。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM