我可以为Spring FileSystemResource使用基于环境变量的位置吗?

我要求将所有属性文件存储在目录中。 该目录的位置应存储在系统环境变量中。 在我的应用程序上下文中,我将需要访问此环境变量来创建FileSystemResource bean。 这是我通常拥有的一个例子:

    myprops.properties     

相反,我需要有类似的东西

 ${prop_file_location}/myprops.properties 

prop文件位置是环境变量。 有谁知道这样做的简单方法?

我使用的是spring 2.5.6和java 1.6

UPDATE

我们后来升级到Spring 3.0.X,我们能够利用spring表达式语言。 我们的方法从三个bean简化为以下代码段:

    classpath:defaults.properties file:/a/defined/location/project.properties file:${AN_ENV_CONFIGURED_DIR}/project.properties       

这使我们可以拥有一个开发(第一个默认值)静态知名位置,或者通过env变量配置的部署位置。 配置器按顺序处理这些(即部署优先于默认值)。

我最终采用非程序化方法。 我使用MethodInvoker来检索环境值。 然后我能够将其传递给FileSystemResource。

      NAME_OF_VARIABLE    

虽然我注意到这个问题需要2.5.x,但值得指出的是,Spring 3的EL支持(自2009年11月起可用)将会做出这类事情的简短工作

 @Value("#{ systemProperties['user.home'] }") private String userHome ; 

要么

  

您可以始终扩展FileSystemResource(即PropertiesFileResource),它将通过将属性文件位置系统属性添加到文件路径来初始化自身。

在Spring.Net中,我们有了IVariableSource接口和PropertyPlaceholderConfigurer ,它们能够从环境变量中检索值。 也许Spring Framework for Java中有类似的东西?

编辑:我在java文档中找到了相应的java bean,名为PropertyPlaceholderConfigurer。

例:

使用-DDA_HOME = c:\ temp启动应用程序

c:\ temp必须包含名为“config”的目录

在c:\ temp \ config中,您有app.properties文件(例如)

扩展Spring加载器:

 public class Loader extends org.springframework.beans.factory.config.PropertyPlaceholderConfigurer{ private String appHome; public void setAppHome(String appHome) { this.appHome = appHome; } @Override public void setLocation(Resource location) { if(appHome==null){ throw new RuntimeException("You must specify VM property DA_HOME, this directory must contain " + "another directory, called config, inside the config directory app.properties " + "file must be found with the configuration properties"); } String configurationDirectory = appHome + System.getProperty("file.separator") + "config"; String fileName = location.getFilename(); Resource file = new FileSystemResource( configurationDirectory + System.getProperty("file.separator")+ fileName); super.setLocation(file); } } 

指定新加载器及其配置库: