Spring Boot 3.1 RC1 Docker Compose无法在集成测试中激活求助
我刚阅读了Spring Boot 3.1 RC版本的发布说明,尝试了其中新增的Docker Compose支持特性,自己搭了个简单示例测试。
我的Docker Compose配置如下:
# Define the services/containers to be run services: postgres: image: postgres ports: - "5432:5432" restart: always environment: POSTGRES_PASSWORD: password POSTGRES_DB: productsdb POSTGRES_USER: user volumes: - ./data/postgresql:/var/lib/postgresql - ./pg-initdb.d:/docker-entrypoint-initdb.d labels: org.springframework.boot.service-connection: postgres # org.springframework.boot.ignore: true # ignore container
在application.properties里配置了Docker Compose的激活环境为default和it:
spring.docker.compose.profiles.active=default,it
直接在IDEA中运行主应用类时,控制台显示已加载default环境,功能正常。但在标注了@ActiveProfiles("it")的集成测试中,Docker Compose无法被激活。
集成测试代码如下:
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) @ActiveProfiles("it") class IntegrationTests { ...}
不确定这是设计如此还是我对Spring Boot的Docker Compose支持理解有误,求解答。
问题分析与解决方法
你混淆了Docker Compose自身的profile和Spring的profile两个核心概念:
spring.docker.compose.profiles.active配置的是Docker Compose文件中定义的专属profile(比如对应docker-compose.it.yml这类带profile后缀的配置文件),和Spring的profile不是同一回事;- Spring Boot 3.1的Docker Compose支持默认仅在
defaultSpring profile激活时自动启动容器,其他profile下需要显式开启。
解决方式有两种:
通过配置文件开启:
创建application-it.properties文件,添加以下配置:spring.docker.compose.enabled=true这样当
itSpring profile激活时,Docker Compose会自动启动对应的容器。通过测试注解开启:
在集成测试类上添加@DockerCompose注解,显式启用Docker Compose支持:@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) @ActiveProfiles("it") @DockerCompose class IntegrationTests { ...}注意需要确保项目中引入了Spring Boot Docker Compose Starter依赖。
如果你的Docker Compose文件没有分profile,那么spring.docker.compose.profiles.active配置可以直接去掉,只需要在对应Spring profile的配置中开启spring.docker.compose.enabled=true即可。
内容的提问来源于stack exchange,提问作者Hantsy

