【问题标题】:Override @PropertySource with @TestPropertySource in Spring Boot在 Spring Boot 中使用 @TestPropertySource 覆盖 @PropertySource
【发布时间】:2016-08-05 12:36:16
【问题描述】:

我有我的 Spring Boot 主类:

@SpringBootApplication
@PropertySource("file:/my/file/properties")
public class Application extends SpringBootServletInitializer {

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
        return builder.sources(Application.class);
    }
  //main method
}

我正在从外部文件中读取属性(使用@PropertySource)。现在,我有一个集成测试:

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes= Application.class)
@WebIntegrationTest
@TestPropertySource("file:/my/test/file/properties") // <---
public class MyTest {
  //some tests
}

我需要使用另一个外部属性文件,与Application 类中的@PropertySource 中指示的不同。出于这个原因,我添加了@TestPropertySource,但似乎这个注释并没有覆盖@PropertySource

我能做什么?

提前致谢。

【问题讨论】:

    标签: java spring spring-boot spring-test


    【解决方案1】:

    这样使用:

    @TestPropertySource(locations = "classpath:test.properties")
    

    并将测试属性文件放入src/test/resources

    【讨论】:

    • 我测试过,我的情况适用于:@TestPropertySource(locations = "file:./src/test/resources/application.properties")
    【解决方案2】:

    在 Java8 中,您可以“重复”一个注解,例如:

    @PropertySource(value = "file:./src/main/resources/mydefault.properties")
    @PropertySource(value = "file:./src/test/resources/override.properties", ignoreResourceNotFound = true)
    

    这样,后者会覆盖第一个文件中的属性(如果可用)。

    【讨论】:

    • 对我不起作用,第二个文件不会覆盖第一个文件的属性...
    • 重复注释不会overwrite 或覆盖 - 它adds
    • 实际上为我工作。我有一个模块客户端,它被其他模块使用,然后在我的模块 custom-client-test 中我添加了 override.properties 文件,它真正覆盖了客户端模块中 mydefault.properties 的道具(当然,客户端模块中不存在 override.properties )
    猜你喜欢
    • 2018-09-21
    • 2013-03-12
    • 1970-01-01
    • 2015-05-01
    • 2015-09-20
    • 1970-01-01
    • 2019-11-21
    • 2020-03-15
    • 2012-12-22
    相关资源
    最近更新 更多