Scrivio Interview library
ConceptFoundations5 min read · updated 12 November 2026

Before @ServiceConnection existed, how were container ports passed to Spring, and when is @DynamicPropertySource still needed?

A Testcontainers container maps its port to a random free port on the host, so the connection URL is known only after the container starts and cannot be written in application.properties. Before @ServiceConnection, we passed it to Spring with @DynamicPropertySource: a static method that receives a registry and adds properties such as registry.add("spring.datasource.url", postgres::getJdbcUrl). It is still needed for services that have no built-in connection details support in Spring Boot, and for our own custom properties.

Why this question is asked

Integration tests with real containers have one practical problem to solve before anything else: telling the application where the container is. The answer changed over Spring Boot versions, and many code bases contain both styles, so interviewers ask this to check that we understand the problem itself, not just the annotation that hides it. In this answer, we will see why container ports are random, write the @DynamicPropertySource version, understand when Spring evaluates it, compare it with @ServiceConnection, and look at the cases where @DynamicPropertySource is still the right tool.

1Why Container Ports Are Random

A PostgreSQL container listens on port 5432 inside the container. Testcontainers does not publish that as port 5432 on our machine, because something else might already be using it, such as a local database or another test run in parallel on the same CI agent. Instead, Docker maps the container port to a random free port on the host, for example 49163, and Testcontainers asks Docker which port it got.

So the JDBC URL changes with every run: jdbc:postgresql://localhost:49163/test today, a different port tomorrow. It is known only after the container has started. A static application-test.properties file cannot contain it, which is why we need a way to set properties at runtime.

Java
PostgreSQLContainer<?> postgres = new PostgreSQLContainer<>("postgres:17-alpine");
postgres.start();
postgres.getMappedPort(5432); // 49163, different on each run
postgres.getJdbcUrl(); // jdbc:postgresql://localhost:49163/test?loggerLevel=OFF

2Passing the Port With @DynamicPropertySource

Spring Framework 5.2 added @DynamicPropertySource for this. We write a static method in the test class that takes a DynamicPropertyRegistry and adds properties to it. The values are Suppliers, not strings, which is the important detail we will come back to.

Java
@SpringBootTest
@Testcontainers
class OrderRepositoryIT {
@Container
static PostgreSQLContainer<?> postgres = new PostgreSQLContainer<>("postgres:17-alpine");
@DynamicPropertySource
static void datasource(DynamicPropertyRegistry registry) {
registry.add("spring.datasource.url", postgres::getJdbcUrl); // a Supplier, read later
registry.add("spring.datasource.username", postgres::getUsername);
registry.add("spring.datasource.password", postgres::getPassword);
}
@Autowired OrderRepository orders;
@Test void savesAndFinds() {
orders.save(new Order(42L));
assertEquals(1, orders.count()); // against the real PostgreSQL in the container
}
}

Notice that the method and the container field are static. Spring calls the method while it builds the application context, before any test instance exists, so it can only reach static state. The properties it adds have higher precedence than application.properties and other property sources, so they override any datasource URL configured there.

3When Spring Reads the Values

The order of events explains why Suppliers are used. The @Testcontainers extension starts the static container before the test class runs. Spring then prepares the context and registers our dynamic property source. Only when a bean, here the DataSource, actually asks for spring.datasource.url does Spring call postgres::getJdbcUrl, and by then the container is running and the mapped port is known.

If we passed postgres.getJdbcUrl() as a plain value at the wrong moment, before the container started, we would get an exception or a wrong URL. The Supplier delays the question until the answer exists. The same mechanism also means the properties become part of the context's cache key, so test classes with the same dynamic property methods and the same containers can share a cached context.

Step throughHow the container's port reaches the DataSource
JUnitTestcontainersSpring contextDataSource
start static container
Docker maps 5432 to 49163
build context, call @DynamicPropertySource
register suppliers for datasource properties
create DataSource bean
read spring.datasource.url
supplier: getJdbcUrl()
jdbc:postgresql://localhost:49163/test

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

4What @ServiceConnection Changed

Spring Boot 3.1 introduced connection details: objects such as JdbcConnectionDetails that describe how to connect to a service, which auto-configuration reads instead of reading properties. @ServiceConnection on a container field tells Spring Boot to create those details from the container. For a PostgreSQLContainer, Boot knows which getters provide the URL, user and password, so the @DynamicPropertySource method disappears.

Java
@SpringBootTest
@Testcontainers
class OrderRepositoryIT {
@Container
@ServiceConnection
static PostgreSQLContainer<?> postgres = new PostgreSQLContainer<>("postgres:17-alpine");
// no datasource properties needed
}

Boot supports many containers this way, including PostgreSQL, MySQL, MongoDB, Redis, Kafka, RabbitMQ and Elasticsearch, and a GenericContainer can be matched by naming the service. For those, @ServiceConnection is shorter and less error-prone than writing properties by hand.

5When @DynamicPropertySource Is Still Needed

There are two common cases. The first is a service that Spring Boot has no connection details support for: for example a custom container running a partner's mock server, LocalStack for an AWS service that our code configures through its own properties, or WireMock running in a container. Boot does not know which properties our code reads for them, so we tell it.

The second is our own custom properties. Even with a supported database, our application might read app.reports.base-url or app.search.endpoint, which no connection details type covers. Both styles combine fine in one test class.

Java
@Container @ServiceConnection
static PostgreSQLContainer<?> postgres = new PostgreSQLContainer<>("postgres:17-alpine");
@Container
static GenericContainer<?> rates = new GenericContainer<>("wiremock/wiremock:3.9.1").withExposedPorts(8080);
@DynamicPropertySource
static void customProps(DynamicPropertyRegistry registry) {
registry.add("app.rates.base-url", () -> "http://" + rates.getHost() + ":" + rates.getMappedPort(8080));
}
Which mechanism to use
SituationUseReason
PostgreSQL, Kafka, Redis and similar@ServiceConnectionBoot builds the connection details
Container Boot does not know@DynamicPropertySourcewe name the properties
Our own app.* properties@DynamicPropertySourceno connection details type covers them
Spring Boot before 3.1@DynamicPropertySourceconnection details did not exist

Notice that we use getHost() rather than writing localhost. On some CI setups, Docker runs on a remote host, and getHost() returns the right address there too.

6Follow-up questions

Why must the @DynamicPropertySource method be static?

Because Spring calls it while building the application context, which happens before a test instance is created and may be shared by several test classes. A static method can only use static fields, which is why the container is static too.

Can a Spring bean register dynamic properties?

Since Spring Framework 6.2, a DynamicPropertyRegistrar bean can add properties from inside the context, which is useful when containers are declared as beans in a @TestConfiguration. Check your version.

What did people do before Spring 5.2?

They used an ApplicationContextInitializer that read the container's URL and added it with TestPropertyValues, referenced through @ContextConfiguration(initializers = ...). It worked but was more verbose.

7Conclusion

In this answer, we saw that Testcontainers maps container ports to random host ports, so connection properties are known only after the container starts. @DynamicPropertySource solves this with a static method that registers Suppliers, which Spring reads when beans need them. Since Spring Boot 3.1, @ServiceConnection builds connection details for supported containers without any properties, while @DynamicPropertySource remains the tool for unsupported services and for custom properties.

What to say in the interviewAbout 70 seconds aloud

Open with

Testcontainers maps the container's port, say 5432, to a random free port on the host, so parallel runs and local services never clash. That means the JDBC URL is only known after the container starts and cannot sit in a properties file.

Then, if they want more

Before @ServiceConnection we used @DynamicPropertySource: a static method in the test class that receives a DynamicPropertyRegistry, and we add properties like registry.add("spring.datasource.url", postgres::getJdbcUrl), plus username and password. The values are Suppliers, so Spring asks for them only when the DataSource bean is created, when the container is already running, and they override application properties.

Since Spring Boot 3.1, @ServiceConnection on the container field creates connection details such as JdbcConnectionDetails directly from the container, so for PostgreSQL, Kafka, Redis and the other supported services no properties are needed.

I still use @DynamicPropertySource for containers Boot has no connection details for, like a WireMock or LocalStack container that my code configures through its own properties, and for custom application properties such as a base URL. Both can be combined in the same test class.

About this answer

Last updated
12 November 2026
Versions it names
Spring Boot 3.1, Spring Framework 5, Spring Framework 6
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.
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 "Before @ServiceConnection existed, how were container ports passed to Spring, and when...": https://scrivio-interview-library.netlify.app/java/integration-testing/5fc2ac5827/