SpringBootTest多方式指定Profile的排列顺序规则咨询
Spring多来源激活Profile的排序规则说明
问题复现场景
- 运行环境:SpringBoot 2.7.1,集成Spring Cloud Config
- 测试类定义如下:
@ActiveProfiles({"local","h2dbmem"}) @SpringBootTest(properties = {"server.ssl.enabled=false"}) @AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE) @TestPropertySource(locations = "classpath:application-integrationtest.properties") public class SystemTest { ... }
- Maven测试执行命令:
mvn -Dspring.profiles.include=cloudconfig clean verify
- 实际运行激活Profile日志:
The following 3 profiles are active: "cloudconfig", "local", "h2dbmem"
- 最初预期的激活顺序:
The following 3 profiles are active: "local", "h2dbmem", "cloudconfig"
- 核心疑问:通过注解、命令行等不同方式指定激活Profile时,是否有明确的排列/加载顺序规则(不涉及属性加载优先级问题)。
排序规则说明
Spring测试上下文框架对多来源Profile的合并排序有固定实现规则,核心逻辑为Profile来源的作用域优先级越高,在最终激活列表中位置越靠前,加载时间越早。越靠后加载的Profile,其中的配置会覆盖前面已加载Profile的同名配置,这也和观察到的h2dbmem中JDBC配置生效、cloudconfig中对应配置被覆盖的结果完全吻合。
不同来源的优先级从高到低(对应激活列表从前到后的顺序)如下:
- 最高优先级(列表最前):测试上下文启动前就已存在的环境级配置,包括命令行传入参数、Maven透传的系统属性、系统环境变量中指定的
spring.profiles.active/spring.profiles.include配置的Profile。传入的cloudconfig属于该层级,因此排在激活列表第一位。 - 第二优先级:测试类上
@SpringBootTest等Spring Boot测试注解的properties字段中声明的spring.profiles.active/spring.profiles.include对应的Profile。 - 第三优先级:测试类上
@ActiveProfiles注解声明的Profile,会严格按照注解中数组的书写顺序,追加到前两层收集到的Profile列表之后。声明的local、h2dbmem就属于该层级,因此按顺序排在cloudconfig之后。 - 最低优先级(列表最后):
@TestPropertySource加载的外部配置文件中声明的spring.profiles.active/spring.profiles.include对应的Profile。
同一来源内声明的多个Profile不会被重排,会严格按照声明顺序加入激活列表。
之前的预期偏差来自于颠倒了环境级配置和测试类注解配置的优先级:命令行传入的Profile属于全局环境级配置,优先级高于测试类上的注解声明,因此会排在激活列表更靠前的位置,而非追加到注解声明的Profile之后。
内容的提问来源于stack exchange,提问作者jmsjr
相关产品推荐
相关产品推荐

