【问题标题】:Spring properties priority弹簧属性优先级
【发布时间】:2012-11-27 09:17:58
【问题描述】:

我有标准的 maven 文件夹结构:

src/main/java  
src/main/resources  
src/test/java  
src/test/resources  

我的 appicationContext 包含以下内容:

<!-- load properties files -->
<context:property-placeholder location="classpath*:*.properties"/>

我已经定义了 2 个hibernate.properties 文件——一个用于src/main/resources,一个用于src/ test/resources。我预计当我运行测试时,我的测试hibernate.properties 将覆盖生产hibernate.properties。而不是加载两个文件并使用生产版本:

Loading properties file from file [D:\projects\video_crawler_v3\out\test\core\hibernate.properties]
Loading properties file from file [D:\projects\video_crawler_v3\out\production\core\hibernate.properties]  

如何正确设置我的属性文件?我正在使用 Intellij IDEA 编译和运行测试

【问题讨论】:

  • 您可以添加您的hibernate.properties 文件的示例吗?我只想看看您的主要配置和测试配置之间的差异。谢谢。
  • 我觉得命名属性占位符配置文件hibernate.properties不是个好主意,`hibernate.properties'一般是Hibernate本身的配置文件,和Spring属性占位符无关.

标签: java spring properties intellij-idea


【解决方案1】:

其中一个选项是 Spring Profiles http://blog.springsource.com/2011/02/11/spring-framework-3-1-m1-released/

在您的 context.xml 中放置两个“属性”版本,例如:

<beans>

   ... your beans

    <beans profile="prod">
        <context:property-placeholder location="classpath:/hibernate.properties" />
    </beans>

    <beans profile="test">
        <context:property-placeholder location="classpath:/test-hibernate.properties" />
    </beans>
</beans>

使用 -Dspring.profiles.active=test 激活所需的配置文件。

注意:使用 www.springframework.org/schema/beans/spring-beans-3.1.xsd

【讨论】:

  • 您应该在这里演示 Spring Profiles 如何成为解决方案。另外需要注意的是:该功能仅适用于 Spring 3.1 及更高版本。
  • 如果你使用的是TextContext框架static.springsource.org/spring/docs/current/…,你可以使用@ActiveProfiles("test")而不是-Dspring.profiles.active=test
【解决方案2】:

src/main/resources 中的文件总是添加到类路径中,即使在运行单元测试时也是如此。看到这个:Common strategies when defining Spring beans for different environments

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-11-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-16
    • 2011-10-23
    • 2022-06-18
    • 1970-01-01
    相关资源
    最近更新 更多