Spring:根据配置文件注入不同的属性文件

Jor*_*ris 14 java google-app-engine spring

首先,一些背景:

我目前正在开发一个项目,我在其中使用Google的AppEngine(GAE)上的Spring框架从Google的一项服务中获取一些数据.为此,我使用了Google的OAuth工具.对于这一点,我需要使用clientSecretclientId特定于我的应用程序.由于这些是静态配置值,我使用Spring <util:properties>(链接到文档)功能将这些值插入到适当的类中.

XML配置:

<util:properties id="googleProperties" location="WEB-INF/google.properties" />
Run Code Online (Sandbox Code Playgroud)

课程用法:

@Value("#{googleProperties['google.data.api.client.id']}")
private String clientId;
Run Code Online (Sandbox Code Playgroud)

我的问题:

事实证明,生产(在App Engine上部署时)和开发(在我的本地机器上)的价值clientIdclientSecret需要不同.为了解决这个问题而不需要在部署时不断更改属性文件中的值,我一直在研究Spring的配置profiles,它允许我为生产和开发指定不同的属性文件.虽然我知道Spring配置文件是如何基于文档工作的,但我不确定在这种特定情况下适当的解决方案是什么.

换句话说,我如何根据我的应用程序是在本地部署还是在GAE上注入不同的属性文件?

tol*_*ius 13

有两种选择:


系统变量

您可以使用前缀来控制特定于环境的属性,这可以通过使用系统变量来完成:

 <util:properties id="googleProperties" 
                  location="WEB-INF/${ENV_SYSTEM:dev}/google.properties" />
Run Code Online (Sandbox Code Playgroud)

在这种情况下,它总是在下面看:

 <util:properties id="googleProperties" 
                  location="WEB-INF/dev/google.properties" />
Run Code Online (Sandbox Code Playgroud)

默认情况下,除非ENV_SYSTEM设置了系统变量.qa例如,如果设置为,它将自动显示在:

 <util:properties id="googleProperties" 
                  location="WEB-INF/qa/google.properties" />
Run Code Online (Sandbox Code Playgroud)

弹簧轮廓

另一种方法是使bean配置文件具体化.例如:

<beans profile="dev">
    <util:properties id="googleProperties" 
                     location="WEB-INF/google-dev.properties" />
</beans>

<beans profile="qa">
    <util:properties id="googleProperties" 
                     location="WEB-INF/google-qa.properties" />
</beans>
Run Code Online (Sandbox Code Playgroud)

googleProperties根据配置文件集加载适当的.例如,这将加载WEB-INF/google-dev.properties:

GenericXmlApplicationContext ctx = new GenericXmlApplicationContext();
ctx.getEnvironment().setActiveProfiles( "dev" );
ctx.load( "classpath:/org/boom/bang/config/xml/*-config.xml" );
ctx.refresh();
Run Code Online (Sandbox Code Playgroud)