我有一个带有自定义配置设置的 Spring 启动应用程序,如下所示:
src/main/resources
├── application.properties
├── config1
│ ├── application-dev.properties
│ ├── application-prod.properties
│ └── application.properties
├── config2
│ ├── application-dev.properties
│ ├── application-prod.properties
│ └── application.properties
└── config3
├── application-dev.properties
├── application-prod.properties
└── application.properties
在运行时指定要使用的配置为:
java -jar
-Dspring.profiles.active=dev
-Dspring.config.name=application,config1/application
target/my-application.0.0.1.jar
如何为@SpringBootTest
指定此内容?我尝试使用@TestPropertySources
但它不起作用:
@SpringBootTest
@ActiveProfiles("prod")
@TestPropertySources({
@TestPropertySource("classpath:application.properties"),
@TestPropertySource("classpath:application-${spring.profile.active}.properties"),
@TestPropertySource("classpath:config1/application.properties"),
@TestPropertySource("classpath:config1/application-${spring.profile.active}.properties"),
@TestPropertySource("classpath:config2/application.properties"),
@TestPropertySource("classpath:config2/application-${spring.profile.active}.properties"),
@TestPropertySource("classpath:config3/application.properties"),
@TestPropertySource("classpath:config3/application-${spring.profile.active}.properties")
})
Spring Boot 允许在@SpringBootTest
和@TestPropertySource
中指定属性,可以利用这些属性来指定spring.config.name
属性。例如,以下内容使用dev
配置文件加载所有配置:
@SpringBootTest(properties = {
"spring.config.name=config1/application,config2/application,config3/application,application"
})
@ActiveProfiles("dev")
这很可能有效,因为这些属性在此处指定的顺序中具有较高的优先级。