在Spring上下文中导入/过滤属性

时间:2012-08-14 17:52:50

标签: java spring

我正在使用Java 1.6和Spring 3.1.1。我正在尝试将外部属性文件读入Spring上下文。这是关键点:第一个属性文件包含下一个属性文件的路径。例如:

$ {user.home}中的第一个属性文件:

resource.dir=C:/users/smith
config.dir=${resource.dir}/configuration

第二个属性文件$ {config.dir}(在第一个属性文件中定义):

datasource.name=jdbc:mysql://dbserver:3306/test
datasource.prop1=etc
datasource.prop2=etc

所以我需要读取第一个文件,处理这些属性,并使用它们来获取第二个文件。

使用Spring PropertyPlaceholderConfigurer只能将我带到第一个文件。我已经读过你在app环境中只能有一个PropertyPlaceholderConfigurer,这似乎是真的。 [编辑:有关说明,请参阅https://jira.springsource.org/browse/SPR-6428。]

有人知道最好的方法吗?

编辑:如果你在ant中运行构建,这显然很容易,不幸的是我的项目使用了Maven。您可以使用PROPERTY标记执行第一步,并“自动”解析下一步的所有内容,允许您将类路径设置为$ {cfg.dir}目录等。然后,您可以从“正常”读取属性这些目录。我希望Spring或Maven允许我使用相同的功能,但还没有找到答案......

ANT示例:

<property file="${user.home}/global.properties" />

<target name="run-some-stuff">
    <java classname="com.mystuff.App" failonerror="true" fork="yes">
        <classpath>
            <path location="${cfg.dir}" />
            <path location="${resource.dir}" />
        </classpath>
        </java>
    </target>

1 个答案:

答案 0 :(得分:1)

如果资源目录只是用户的主目录,则可以在xml中执行以下操作...

<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd">

  <context:property-placeholder location="file:${user.home}/configuration"/>
</beans>

或者,如果您希望在代码中执行此操作,还可以使用@PropertySource注释

这是有效的,因为在Spring 3.1中,PropertySource抽象统一了系统属性,环境变量以及属性文件的属性。 user.home是一个系统属性。