【问题标题】:@ActiveProfile and spring.profiles.active@ActiveProfile 和 spring.profiles.active
【发布时间】:2013-02-20 03:04:17
【问题描述】:

这是我的 applicationContext 定义的一部分,用于检索一些属性。

 <!-- get some properties -->
<context:property-placeholder
        ignore-resource-not-found="false" ignore-unresolvable="false"
        location="classpath:/properties/${spring.profiles.active:test}/some.properties"/>

如您所见,我让 spring.profiles.active 决定将读取哪些属性。 我的测试带有注释:

@ActiveProfile("integration")

您猜对了,我的 spring bean 配置文件实际上与部署/测试应用程序的环境相匹配。 我的位置属性仍然被解析为“/properties/test/some.properties”。这当然是因为 spring.profiles.active 在这种情况下似乎没有得到解决。

我怎样才能获得正确的属性?

【问题讨论】:

    标签: spring properties configuration applicationcontext profiles


    【解决方案1】:

    这是因为活动配置文件可能由系统属性激活(但在 @ActiveProfiles 的情况下,它以另一种方式工作)。

    就像这样:

    <beans profile="dev,prod,qa">
        <context:property-placeholder location="classpath:some.properties" ignore-unresolvable="true"/>
    </beans>
    
    <beans profile="test">
        <context:property-placeholder location="classpath:some-test.properties" ignore-unresolvable="true"/>
    </beans>
    

    另外,您可以尝试更改 location="classpath:/properties/${spring.profiles.active:test}/some.properties"location="classpath:/properties/${spring.profiles.active}/some.properties"

    【讨论】:

    • 这确实是我也在考虑的一种解决方法,但这对我来说仍然是@ActiveProfile 注释实现中的一个错误。为了完整起见,我本来希望它设置 spring.profiles.active 属性。我不喜欢写很多 xml。
    • 在这种情况下,您可以添加自定义 JUnitTestRunner 并根据@ActiveProfiles 设置系统属性
    • 我们还可以使用@PropertySource 设置属性源,并确保我们的PropertyPlaceHolder 不会抱怨缺少属性文件。但关键是失去了拥有这个属性。
    【解决方案2】:

    见票:https://jira.springsource.org/browse/SPR-8982#comment-88498

    有人已经提出了这个要求:

    通过“-Dspring.profiles.active”或其他系统属性从命令行覆盖由测试在运行时指定的@ActiveProfile的选项

    我的评论:

    或者它应该设置属性 spring.profiles.active。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-01-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-29
      • 1970-01-01
      • 2020-06-06
      相关资源
      最近更新 更多