我在 Spring 遇到了这个进行属性替换
<context:property-placeholder location="esb-project-config.properties"/>
但不幸的是,我们不希望在 xml 文件中出现这种情况,因为我们想在测试中重复使用该文件,但在 test.properties 文件中进行交换以进行测试。 IE。我们想测试所有的生产绑定(bind),但要使用适合测试的属性,例如 localhost。我们如何加载 ApplicationContext 但使用不同的属性文件?
谢谢, 院长
最佳答案
几种方法:
1。 “订单”属性
在 src/main/resources/your-conf.xml
<context:property-placeholder
location="classpath:esb-project-config.properties"
order="1"/>
在 src/test/resources/your-test-config.xml
<context:property-placeholder
location="classpath:esb-project-config.properties"
order="0"/>
如果您使用 src/test/resources
作为测试类路径来运行测试,以上将确保覆盖 src/main/resources/esb-project-config.properties
与 src/test/resources/esb-project-config.properties
。
不过,这将覆盖整个 property-placeholder
,因此您必须提供应用程序中所需的所有属性来进行此测试 property-placeholder
。例如
<context:property-placeholder
location="classpath:esb-project-config.properties,
classpath:some-other-props-if-needed.properties"
order="0"/>
2。 PropertyOverrideConfigurer
<context:property-override
location="classpath:esb-project-config.test.properties"/>
覆盖某些个人属性。一些例子here
3。系统变量
您可以使用前缀来控制特定于环境的属性,这可以通过使用系统变量来完成:
<context:property-placeholder
location="${ENV_SYSTEM:dev}/esb-project-config.properties"/>
在这种情况下,它将始终查看:
<context:property-placeholder
location="dev/esb-project-config.properties"/>
默认情况下,除非设置了 ENV_SYSTEM
系统变量。如果设置为qa
,比如会自动往下看:
<context:property-placeholder
location="qa/esb-project-config.properties"/>
4。 Spring 型材
另一种方法是使 bean 配置文件特定。例如:
<beans profile="dev">
<context:property-placeholder
location="esb-project-config.dev.properties"/>
</beans>
<beans profile="qa">
<context:property-placeholder
location="esb-project-config.qa.properties"/>
</beans>
将根据配置文件集加载适当的 esb-project-config
。例如,这将加载 esb-project-config.dev.properties
:
GenericXmlApplicationContext ctx = new GenericXmlApplicationContext();
ctx.getEnvironment().setActiveProfiles( "dev" );
ctx.load( "classpath:/org/boom/bang/config/xml/*-config.xml" );
ctx.refresh();
- 注意:“系统变量”和“系统配置文件”方法通常用于在不同的环境之间切换,而不仅仅是开发模式下的“开发 <==> 测试”,但仍然是有用的功能要注意。
关于用于测试和生产的 Spring 属性替换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9470551/