在 Spring Boot 中用 @TestPropertySource 覆盖 @PropertySource

Override @PropertySource with @TestPropertySource in Spring Boot

我有我的 Spring Boot main class:

@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 class 中的 @PropertySource 中指示的不同。出于这个原因,我添加了 @TestPropertySource,但似乎此注释并未覆盖 @PropertySource.

我能做什么?

提前致谢。

这样使用:

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

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

在 Java8 中,您可以 "repeat" 像这样的注释:

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

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