Spring 3.1.4结合@ServiceConnection与Testcontainers遇端口映射启动报错
解决Spring Boot 3.1.4 + Testcontainers @ServiceConnection 端口获取错误
问题根因
你遇到的Mapped port can only be obtained after the container is started错误,是因为同时使用了@ServiceConnection和Testcontainers JDBC URL配置导致的冲突:
@ServiceConnection是Spring Boot 3.1+提供的自动配置能力,会自动启动Testcontainers容器并替换数据源的连接参数;- 你在
test.yml中配置的jdbc:tc:postgresql:13.5:///helloTalk是Testcontainers JDBC驱动的自定义URL格式,会由驱动自行启动容器。
两种方式同时生效时,Spring Boot在初始化数据源时,容器还未完成启动就尝试获取映射端口,从而抛出异常。
解决方案
1. 删除test.yml中的数据源配置
完全移除spring.datasource相关配置,@ServiceConnection会自动为你配置数据源的URL、驱动类名、用户名和密码:
# 移除以下配置 # spring: # datasource: # type: com.zaxxer.hikari.HikariDataSource # driver-class-name: org.testcontainers.jdbc.ContainerDatabaseDriver # url: jdbc:tc:postgresql:13.5:///helloTalk
2. 确认容器配置的静态属性
你的BasePostgresConfig中的容器定义已经是static的,这是正确的——静态容器会在测试类加载时初始化,确保Spring Boot能在数据源初始化前启动容器:
public class BasePostgresConfig { @Container @ServiceConnection static PostgreSQLContainer<?> postgres = new PostgreSQLContainer<>("postgres:13.5"); }
3. 移除不必要的注解
不需要在BasePostgresConfig上添加@ActiveProfiles("test"),除非你有其他测试环境的配置需要启用,数据源部分已经由@ServiceConnection自动处理。
验证修改
完成上述修改后,重新运行测试:
- Spring Boot会自动启动PostgreSQL容器;
@ServiceConnection会将数据源的连接参数替换为容器的实际地址、端口等信息;- 数据源初始化时容器已启动,端口可以正常获取。
内容的提问来源于stack exchange,提问作者Francislainy Campos
相关产品推荐
相关产品推荐

