Skip to content
javahacks.dev
Testing

How to Use Testcontainers With Spring Boot ServiceConnection

Wire Testcontainers into Spring Boot tests with @ServiceConnection: no dynamic properties, supported containers, local development with TestApplication.

7 min read
Summarize in AI
Flat illustration of a test report with one failing test, with the Spring Boot, GitHub Actions, JUnit5 and Jenkins logos.

Before Spring Boot 3.1, wiring a container into a test meant copying its URL, user and password into Spring properties by hand. @ServiceConnection removes that step. This uses Spring Boot 4, Testcontainers and JUnit Jupiter 6 on JDK 25. The container basics are in Testcontainers for databases.

The old way

java
@Testcontainers
@SpringBootTest
class OrderIT {

    @Container
    static PostgreSQLContainer<?> db = new PostgreSQLContainer<>("postgres:17-alpine");

    @DynamicPropertySource
    static void props(DynamicPropertyRegistry r) {
        r.add("spring.datasource.url", db::getJdbcUrl);
        r.add("spring.datasource.username", db::getUsername);
        r.add("spring.datasource.password", db::getPassword);
    }
}

Every container needed its own mapping, and the property names had to be right for each technology.

With ServiceConnection

java
@Testcontainers
@SpringBootTest
class OrderIT {

    @Container
    @ServiceConnection
    static PostgreSQLContainer<?> db = new PostgreSQLContainer<>("postgres:17-alpine");

    @Autowired OrderRepository orders;

    @Test
    void savesAndLoads() {
        var saved = orders.save(new Order("ada"));
        assertThat(orders.findById(saved.getId())).isPresent();
    }
}

Boot sees a PostgreSQLContainer annotated with @ServiceConnection, creates a JdbcConnectionDetails bean from it, and the datasource auto-configuration uses it in place of properties. No URL, no username. The connection details beans take priority over spring.datasource.*, so a stray local property will not point the test at another database.

Supported containers

ContainerConfigures
PostgreSQLContainer, MySQLContainer, MariaDBContainer, OracleContainer, MSSQLServerContainerJDBC and R2DBC datasource
GenericContainer with RedisContainer image (redis)Spring Data Redis
KafkaContainerKafka bootstrap servers
RabbitMQContainerRabbitMQ connection
MongoDBContainer, Neo4jContainer, CassandraContainerRespective Spring Data stores
ElasticsearchContainerElasticsearch client

For a GenericContainer, give the connection name: @ServiceConnection(name = "redis"). The list grows with releases, so check the reference for yours.

Shared containers in a configuration class

Declare containers as beans to share them among test classes:

java
@TestConfiguration(proxyBeanMethods = false)
class Containers {

    @Bean
    @ServiceConnection
    PostgreSQLContainer<?> postgres() {
        return new PostgreSQLContainer<>("postgres:17-alpine");
    }

    @Bean
    @ServiceConnection
    KafkaContainer kafka() {
        return new KafkaContainer(DockerImageName.parse("apache/kafka:4.0.0"));
    }
}

@SpringBootTest
@Import(Containers.class)
class CheckoutIT { }

Spring manages the lifecycle: a container bean starts with the application context and stops when it closes. Because Spring caches contexts across tests with the same configuration, the containers are reused as long as the context is. Mismatched configurations create new contexts and new containers, which is a reason to keep test configuration consistent. See sharing containers across tests for cost control.

Local development with the same containers

The same configuration can start the real application with containers, replacing a hand maintained Docker Compose file:

java
public class TestShopApplication {

    public static void main(String[] args) {
        SpringApplication.from(ShopApplication::main)
                .with(Containers.class)
                .run(args);
    }
}

Run TestShopApplication from the IDE and the application starts with a fresh database and broker. Add .withReuse(true) and @RestartScope to keep the container across devtools restarts. The Maven plugin runs it with ./mvnw spring-boot:test-run. This also pairs with Spring Boot's Docker Compose support as an alternative.

Startup detail

Annotated static fields in the test class need @Testcontainers and @Container, which manage the lifecycle. If you use @Bean, Spring manages it, and no @Container is needed. Mixing both for the same container starts it twice.

Problems

If the connection details are not applied, check that the container type is on the supported list and that spring-boot-testcontainers is a test dependency. Beyond that, an image pull failure or a missing Docker socket gives the errors in that fix. Slices such as @DataJpaTest work too, with @AutoConfigureTestDatabase(replace = NONE).

A test that runs against a real PostgreSQL, with no URL anywhere

The point of @ServiceConnection is what is missing from the test: there is no datasource URL, no username and no @DynamicPropertySource. This test uses Spring Boot 4.0.9 with Testcontainers 2.x, on a machine with Docker running, and the application has no database configured for tests.

src/test/java/dev/javahacks/PostgresIT.javajava
@SpringBootTest(properties = "spring.jpa.hibernate.ddl-auto=create")
@Testcontainers
class PostgresIT {

    @Container
    @ServiceConnection
    static PostgreSQLContainer postgres = new PostgreSQLContainer("postgres:17-alpine");

    @Autowired JdbcTemplate jdbc;

    @Test
    void usesTheContainerWithoutAnyDatasourceProperty() {
        String version = jdbc.queryForObject("select version()", String.class);
        System.out.println("CONNECTED TO: " + version.substring(0, 24));
        assertThat(version).startsWith("PostgreSQL 17");
    }
}
XML
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-testcontainers</artifactId><scope>test</scope></dependency>
<dependency><groupId>org.testcontainers</groupId><artifactId>testcontainers-junit-jupiter</artifactId><scope>test</scope></dependency>
<dependency><groupId>org.testcontainers</groupId><artifactId>testcontainers-postgresql</artifactId><scope>test</scope></dependency>
<dependency><groupId>org.postgresql</groupId><artifactId>postgresql</artifactId><scope>test</scope></dependency>
Text
INFO tc.testcontainers/ryuk:0.14.0 -- Creating container for image: testcontainers/ryuk:0.14.0
INFO tc.postgres:17-alpine -- Creating container for image: postgres:17-alpine
INFO tc.postgres:17-alpine -- Container is started (JDBC URL: jdbc:postgresql://localhost:62688/test?loggerLevel=OFF)
CONNECTED TO: PostgreSQL 17.11 on aarc
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 4.602 s

The container got a random host port (62688 in this run), the application context received a URL, user and password derived from the container, and the query ran against PostgreSQL 17.11. In Testcontainers 2, the module classes moved: the container is org.testcontainers.postgresql.PostgreSQLContainer, the artifact is testcontainers-postgresql, and the class is no longer generic, so code copied from 1.x tutorials fails to compile on the import. The ryuk container in the log is Testcontainers' cleanup helper, which removes your containers even if the JVM is killed.

One failure appeared on the way and is worth recording. The first version of the test used webEnvironment = NONE, and the context failed with Parameter 0 of method openChain required a bean of type 'HttpSecurity' that could not be found. The application's security configuration needs a web environment, which NONE removes. The error was in the test setup, not in Testcontainers, which is typical: when a context fails after the container started, read the failure report for the first bean named.

What the annotation replaces

The older form needed a static method to copy the container's values into the Spring environment, one property at a time.

java
@DynamicPropertySource
static void props(DynamicPropertyRegistry registry) {
    registry.add("spring.datasource.url", postgres::getJdbcUrl);
    registry.add("spring.datasource.username", postgres::getUsername);
    registry.add("spring.datasource.password", postgres::getPassword);
}

Each new container type needed its own list, and a mistyped property name produced a context that quietly used an in-memory database. @ServiceConnection knows the properties for each supported container: PostgreSQL, MySQL, MariaDB, MongoDB, Redis, Kafka, RabbitMQ, Elasticsearch and more. For a container it does not support, @DynamicPropertySource remains the tool.

Share one container across test classes

A container started per class costs seconds each. Declare it once in a shared configuration and import it.

java
@TestConfiguration(proxyBeanMethods = false)
class Containers {

    @Bean
    @ServiceConnection
    PostgreSQLContainer postgres() {
        return new PostgreSQLContainer("postgres:17-alpine");
    }
}
java
@SpringBootTest
@Import(Containers.class)
class OrderRepositoryIT { }

Spring caches the context across tests with the same configuration, so the container starts once per context. The same Containers class can start the application for development with SpringApplication.from(Application::main).with(Containers.class).run(args), so developers get the same database the tests use, without a local install.

Running the same containers while developing

The configuration class that starts containers for tests can also start them for local development, which gives the team a database that needs no installation and no shared state. In Spring Boot, a test-scope main method launches the application with the containers attached.

src/test/java/dev/javahacks/TestApplication.javajava
public class TestApplication {
    public static void main(String[] args) {
        SpringApplication.from(Application::main).with(Containers.class).run(args);
    }
}

Run it from the IDE and the application starts with a fresh PostgreSQL in a container, using the same version as the tests. Add @RestartScope to the container bean and DevTools keeps it alive across restarts, so a code change does not wipe the data. This removes the differences between local development, tests and CI, as all three use the same image tag, and a database upgrade becomes a one-line change reviewed once.

Keep the container tests fast enough to run

Container tests have a fixed cost, and the cost compounds when every class starts its own context. Three habits keep a suite usable. Share containers through one configuration class so the database starts once. Reuse Spring contexts by keeping the same set of annotations and properties across test classes, because a different properties value creates a new context and a new connection pool. And separate the suites: run unit tests on every save, and the container tests on every commit in CI, where the Docker layers for the image are cached.

Measure rather than guess. Print the time a test run spends starting containers and contexts, and track it. When it passes a threshold your team agrees on, look for a class that introduced its own @DirtiesContext or its own container, which are the usual causes of a suite that doubles in time between releases.

Where this does not apply

Frameworks other than Spring have their own integration, such as Quarkus Dev Services, see Dev Services. The reference is the Boot Testcontainers documentation, with a walk-through in the Testcontainers guides.

Taggedhow to
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.