You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot 3.1 RC1 Docker Compose无法在集成测试中激活求助

Spring Boot 3.1 RC 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支持默认仅在default Spring profile激活时自动启动容器,其他profile下需要显式开启。

解决方式有两种:

  1. 通过配置文件开启:
    创建application-it.properties文件,添加以下配置:

    spring.docker.compose.enabled=true
    

    这样当it Spring profile激活时,Docker Compose会自动启动对应的容器。

  2. 通过测试注解开启:
    在集成测试类上添加@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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 00:32:27