spring框架应用程序的多组配置

时间:2014-01-03 20:19:23

标签: spring configuration playframework configuration-files configuration-management

Play!Framework提供了一个非常好的功能,使您可以配置不同的配置集,因此我可以有类似的东西

storage=fs
storage.fs.home.dir=...
storage.fs.home.url=...
...

%at.storage=s3
%at.storage.s3.key=...
%at.storage.s3.secret=...
...

%prod.storage=s3
%prod.storage.s3.key=...
%prod.storage.s3.secret=...
...

默认情况下,应用程序使用fs(文件系统)存储,如果应用程序使用--%at(验收测试)模式启动,则使用aws s3作为存储实现,如果应用程序以--%prod启动,则生产模式,它也使用s3存储但可以使用不同的S3配置。此功能使得对应用程序配置文件进行版本控制非常容易,在部署到实时服务器或验收测试服务器时无需更新配置文件。

我很好奇有没有人为基于Spring框架的应用程序实现某种机制。

2 个答案:

答案 0 :(得分:1)

看一下Spring的Profiles

在我的应用程序中,我通常有一个default.properties和dev.properties之类的东西,它会覆盖default.properties中的一些值。我使用ProfileResourceProvider启用此功能。

答案 1 :(得分:1)

尝试这样,在类路径的根目录中创建不同的目录,包含不同环境的配置。保留相同的文件名:

.
|____pom.xml
|____src
| |____main
| | |____resources
| | | |____dev 
| | | | |____application.properties
| | | |____test 
| | | | |____application.properties
| | | |____prod 
| | | | |____application.properties

然后在应用程序启动时,传入一个环境变量,该变量指出要使用的环境。例如:

-Denv=prod

根据环境变量使用util:properties配置给定属性文件的加载:

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

    <util:properties id="application" location="classpath:${env}/application.properties"/>

    ... remaining config here

</beans>