如何按环境加载弹簧加载配置文件?

时间:2015-10-17 12:58:26

标签: java spring maven

我在我的应用程序中使用spring框架,并且我使用了一些配置文件,但在不同的环境中,我需要使用不同的属性,如db config properties。现在我将不同的文件放在不同的路径中,然后我使用maven { {1}}打包不同WAR的方法。

现在,我想在所有环境中只打包一个WAR,并希望通过传输不同的参数来使用不同的配置文件。此外,我不想将配置文件放在项目之外。

2 个答案:

答案 0 :(得分:1)

您可以使用spring bean配置文件或条件bean。您可以使用以下配置为每个环境定义propertyplaceholder bean。

        <beans profile="environment1">
<bean 
    class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">

    <property name="location">
        <value>database_env1.properties</value>
    </property>
</bean>
</beans>

<beans profile="environment2">
<bean 
    class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">

    <property name="location">
        <value>database_env2.properties</value>
    </property>
</bean>
</beans>

答案 1 :(得分:1)

对于数据库配置,一种可能的方法是直接在您使用的应用程序服务器中将JDBC DataSource定义为JNDI资源(see how) - 这样您的WAR文件就不包含连接信息,运行时环境确实包含此信息。

这种方法的一个优点是,连接信息可以由服务器管理员而不是应用程序开发人员进行管理。

不确定它是否符合您的项目以外的任何配置&#34;但要求。