Scrivio Interview library
CodingFoundations5 min read · updated 12 November 2026

Show how to use a PostgreSQL Testcontainers container with @ServiceConnection in a Spring Boot test, and explain what @ServiceConnection replaces.

In a @Testcontainers test class we declare @Container @ServiceConnection static PostgreSQLContainer<?> postgres = new PostgreSQLContainer<>("postgres:17"). @ServiceConnection, available since Spring Boot 3.1, creates connection details beans from the running container, so the DataSource uses the container's URL, user and password. It replaces the manual @DynamicPropertySource method that set spring.datasource.url and similar properties, and it works for many containers such as PostgreSQL, Kafka, Redis and MongoDB.

Why this question is asked

Testing against the same database engine as production catches the bugs an in-memory database hides: PostgreSQL-specific SQL, constraints, JSON columns and migrations. Testcontainers makes this cheap by starting the real database in Docker for the test. The remaining friction was wiring the container's random port and credentials into Spring, and @ServiceConnection removed it. Interviewers ask this to check that we know the modern setup and what it replaced. In this answer, we will recap Testcontainers, write the test, see what @ServiceConnection does under the hood, compare it with the old approach, and cover versions.

1A Quick Recap of Testcontainers

Testcontainers is a Java library that starts Docker containers from tests and stops them afterwards. A PostgreSQLContainer starts a real PostgreSQL server in a container, waits until it accepts connections, and tells us its JDBC URL, user and password. The port on our machine is random, so two builds on one CI runner never clash.

With JUnit 5, @Testcontainers on the class and @Container on a field let the library manage the lifecycle: a static field starts once for the class and stops after it, an instance field starts for each test method. For a database, static is almost always what we want.

2Writing the Test

We need three test dependencies: spring-boot-testcontainers, the Testcontainers PostgreSQL module, and the Testcontainers JUnit integration. Then the test is short.

Java
@SpringBootTest
@Testcontainers
class OrderRepositoryIT {
@Container
@ServiceConnection
static PostgreSQLContainer<?> postgres = new PostgreSQLContainer<>("postgres:17");
@Autowired OrderRepository orders;
@Test
void savesAndFindsOrder() {
orders.save(new Order(null, "NEW"));
assertThat(orders.findByStatus("NEW")).hasSize(1); // 1, stored in real PostgreSQL 17
}
}

Notice what is missing: no spring.datasource.url, no username, no password. When the context starts, the container is already running, and Spring Boot reads its connection details directly. Flyway or Liquibase migrations then run against it, so the schema is the real one too.

On Testcontainers 2.x, which Spring Boot 4 uses, the module classes moved to new packages and some lost their generic parameter, for example org.testcontainers.postgresql.PostgreSQLContainer; on 1.x it is org.testcontainers.containers.PostgreSQLContainer<?>. Check your version for the import.

3What @ServiceConnection Does

Spring Boot 3.1 introduced connection details, small interfaces that describe how to reach a service, such as JdbcConnectionDetails with a JDBC URL, user name and password. Auto-configuration reads connection details first and properties second. @ServiceConnection tells Spring Boot to create a connection details bean from the annotated container: it looks at the container type, here PostgreSQL, finds the matching factory, and builds JdbcConnectionDetails from the container's getJdbcUrl(), getUsername() and getPassword().

Step throughHow the DataSource gets the container's address
JUnitContainerSpring BootDataSource
start postgres:17 (static @Container)
ready on localhost:55012
start test context
read JDBC URL, user, password
register JdbcConnectionDetails bean
create Hikari pool from connection details
connect, run migrations

7 messages in order. Play them, or step through them one at a time.

No properties are involved; the connection details bean takes precedence over spring.datasource.*.

4What It Replaces

Before Spring Boot 3.1, we wired the container by hand with @DynamicPropertySource, a static method that adds properties to the test's environment after the container has started.

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

This still works and remains useful for containers Boot does not support, or for our own application properties. But it is repetitive, easy to get slightly wrong, for example forgetting one property for a second data source, and it has to be copied for every service type, Kafka bootstrap servers, Redis host and port, and so on. @ServiceConnection does the same job in one annotation.

5Supported Containers and Pinned Versions

Spring Boot supports @ServiceConnection for many containers, among them PostgreSQL, MySQL, MariaDB, Oracle, SQL Server, MongoDB, Kafka, RabbitMQ, Cassandra, Elasticsearch, Neo4j and Redis. For a generic container such as Redis started with GenericContainer, we tell Boot what it is with @ServiceConnection(name = "redis"). Check the Spring Boot documentation for the full list in your version.

Finally, we pin the image version to match production, postgres:17 if production runs PostgreSQL 17, rather than postgres:latest. A floating tag means a build can change behaviour overnight when a new major version is published, and tests against a different version than production give weaker evidence.

6Follow-up questions

Can several test classes share one container?

Yes. Declare the container once, for example as a static field in a shared base class or as a @Bean with @ServiceConnection in a @TestConfiguration that tests import. Then it starts once per JVM and every context that uses it connects to the same database.

Does @DataJpaTest replace the container's DataSource with an embedded database?

Older versions replaced any DataSource by default, so we added @AutoConfigureTestDatabase(replace = NONE). Newer versions leave a DataSource from @ServiceConnection alone; check your version, and keep replace = NONE when you want to be explicit.

What do CI runners need?

A working Docker environment the build can reach, and ideally the pinned images pre-pulled or available from a registry mirror, so tests do not spend minutes downloading images.

7Conclusion

In this answer, we declared a static @Container @ServiceConnection PostgreSQLContainer for postgres:17 in a @Testcontainers test, and saw that @ServiceConnection, since Spring Boot 3.1, turns the container into a JdbcConnectionDetails bean that the DataSource uses instead of properties. It replaces hand-written @DynamicPropertySource methods, supports many containers including PostgreSQL, Kafka, Redis and MongoDB, and works best with image versions pinned to production.

What to say in the interviewAbout 80 seconds aloud

Open with

I would annotate the test class with @SpringBootTest and @Testcontainers, and declare a static field annotated with @Container and @ServiceConnection: a PostgreSQLContainer created with the image postgres:17, matching what production runs.

Then, if they want more

Because the field is static, JUnit starts the container once for the class, before the Spring context. Then I just autowire the repository and test against real PostgreSQL, with Flyway migrations running too.

What @ServiceConnection does is use Spring Boot's connection details abstraction from 3.1: it sees a PostgreSQL container, builds a JdbcConnectionDetails bean from the container's JDBC URL, user name and password, and the DataSource auto-configuration uses that instead of spring.datasource properties. Before 3.1, we wrote a @DynamicPropertySource method that registered spring.datasource.url, username and password from the container's getters.

That still works for custom properties or unsupported containers, but @ServiceConnection removes the boilerplate and works the same way for Kafka, Redis, MongoDB, RabbitMQ and others; for a generic container like Redis I pass name equals redis.

I would always pin the image version rather than using latest, share the container across test classes through a base class or configuration, and note that on Testcontainers 2 the PostgreSQLContainer class moved package.

About this answer

Last updated
12 November 2026
Versions it names
Spring Boot 3.1, PostgreSQL 17, JUnit 5, Spring Boot 4
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Official documentation
Spring Boot reference, Testing
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Show how to use a PostgreSQL Testcontainers container with @ServiceConnection in a...": https://scrivio-interview-library.netlify.app/spring-boot/spring-boot-test/830441d242/