用于测试和生产的 Spring 属性替换

标签 spring

我在 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.propertiessrc/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/

相关文章:

java - 如何解决 java.lang.ClassNotFoundException : org. docx4j.jaxb.ri.NamespacePrefixMapper

spring - 将 @PageableDefault 与 Spring Data REST 结合使用

java - Spring Batch配置异常

java - 如何修复 native 查询 : it is showing syntax error near or at 中的错误

java - Spring Data REST 在哪里构建异常 JSON 回复?

java - Spring Rest路径与@PathVariable和@MatrixVariable冲突

java - 使用 Hibernate 构建服务层

java - 决定在 Spring Boot 应用程序中使用多个实现中的哪一个

spring - Spring Elasticsearch聚合过滤不起作用

spring - 在 Spring 中处理 HTTP 基本授权 header