我需要将我们所有的属性文件都存储在一个目录中。此目录的位置应存储在系统环境变量中。在我的应用程序上下文中,我需要访问这个环境变量来创建 FileSystemResource bean。这是我通常拥有的示例:
<bean id="properties" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<bean class="org.springframework.core.io.FileSystemResource">
<constructor-arg>
<value>myprops.properties</value>
</constructor-arg>
</bean>
</property>
</bean>
相反,我需要让它像
<value>${prop_file_location}/myprops.properties</value>
其中 prop 文件位置是一个环境变量。有谁知道这样做的简单方法?
我正在使用 spring 2.5.6 和 java 1.6
更新
我们后来升级到 Spring 3.0.X,我们能够利用 spring 表达式语言。我们的方法从三个 bean 简化为以下代码段:
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations"> <list> <value>classpath:defaults.properties</value> <value>file:/a/defined/location/project.properties</value> <value>file:${AN_ENV_CONFIGURED_DIR}/project.properties</value> </list> </property> <property name="ignoreResourceNotFound" value="true" /> <property name="searchSystemEnvironment" value="true" /> <property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE" /> </bean>
这使我们可以拥有静态众所周知的开发位置(第一个默认值),或者通过 env 变量配置的部署位置。配置器按顺序处理这些(即部署的优先于默认值)。
老的
我最终采用了非程序化的方法。我使用 MethodInvoker 来检索环境值。然后我能够将它传递到 FileSystemResource 中。
<bean id="configPath" class="org.springframework.beans.factory.config.MethodInvokingFactoryBean" > <property name="targetClass" value="java.lang.String" /> <property name="staticMethod" value="java.lang.System.getenv" /> <property name="arguments"> <list> <value>NAME_OF_VARIABLE</value> </list> </property> </bean>