PropertyPlaceholderConfigurer和.properties文件中的环境变量

时间:2012-04-25 22:25:14

标签: java spring environment-variables applicationcontext properties-file

我有一个带有PropertyPlaceholderConfigurer的Spring application-context.xml,用于从.properties文件中获取属性值。主文件夹和测试源文件夹具有单独的.properties文件。问题是我需要在.properties文件中使用环境变量。但是当我按照以下方式进行时:

property.name=${env.SYSTEM_PROPERTY}

我收到以下错误:

org.springframework.beans.factory.BeanDefinitionStoreException: Invalid bean definition with name 'beanName' defined in class path resource [com/example/applicationContext.xml]: Could not resolve placeholder 'env.SYSTEM_PROPERTY'

而占位符配置器定义为

<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="location" value="classpath:com/example/application.properties"/>
</bean>

任何想法如何使property.name被解释为环境变量(而不是占位符)?

最好的问候,Dmitriy。

3 个答案:

答案 0 :(得分:25)

我可能完全改变了解决方案:直接注入系统属性,而不是注入引用系统属性的属性

E.g。

@Value("#{ systemProperties['JAVA_MY_ENV'] }") 
private String myVar;

<property name ="myVar" value="#{systemProperties['JAVA_MY_ENV']}"/>

我使用像这样的属性占位符配置器

<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
  <property name="locations">
    <list>
        <value>classpath:someprops.properties</value>
    </list>
  </property>
  <property name="ignoreResourceNotFound" value="true" />
  <property name="searchSystemEnvironment" value="true" />
  <property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE" />

您还必须记住使用

将参数传递给程序
 -DJAVA_MY_ENV=xyz

这样,当你运行生产版本时,你可以传递一件事,当你运行另一件事时。

我经常做的事情也是这样的:

  <property name="locations">
    <list>
      <value>classpath:someprops.properties</value>
      <value>classpath:someprops-{environment}.properties</value>
    </list>
  </property>

其中环境是prod / stage / test / int / ci / local(每个环境1个 - 你现在可能只有2个或3个)。您可以将环境变量传递给程序。任何属性都应该相同,无论它在本地pc / tests上的生产/运行是否都在someprops.properties属性文件中。任何特定于环境/运行方式的文件都将放在更具体的文件中(您应该将它放在someprops.properties文件中以及默认情况下除非被覆盖的机制)

E.g。 在classpath中:someprops.properties

url=www.mysite.com
classpath中的

:someprops-local.properties

url=localhost

通过使用这个基本思想,您可以以干净的方式分离测试和程序的正常运行属性。

答案 1 :(得分:9)

使用:

<context:property-placeholder location="classpath:env.properties"/>

改变你的:

property.name=${env.SYSTEM_PROPERTY}

要:

property.name=${SYSTEM_PROPERTY}

我正在使用Spring 3.0.4.RELEASE,但我不知道何时引入它。

答案 2 :(得分:0)

我使用了benkiefer的方法,但我必须在web.xml中添加一个监听器:

<listener>
   <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>