What is a Spring Boot Testcontainers service connection and how does it work?
A service connection lets Spring Boot read connection information directly from a running container. Without it, you copy that information into spring.datasource.* or spring.kafka.* properties yourself. When you annotate a container with @ServiceConnection, Spring Boot uses a factory for that container type to build a ConnectionDetails bean, such as JdbcConnectionDetails for Postgres or KafkaConnectionDetails for Kafka. Auto-configuration then uses that bean instead of the matching properties.
Before and after
The older pattern declares a PostgreSQLContainer and a static @DynamicPropertySource method. That method registers spring.datasource.url, username and password from the container's getters. It works, but you must know which property keys each service needs, and every test class repeats the same wiring.
With a service connection, you put @ServiceConnection on the container field and delete the method. The property names no longer matter, because Spring Boot maps the container to typed connection details. A typo in a property key can no longer leave the test silently pointing at a local database.
container starts (random host port)
│
▼
ConnectionDetails factory for the container type
│
▼
JdbcConnectionDetails / KafkaConnectionDetails bean
│
├──► DataSource auto-configuration
└──► Kafka auto-configuration (producer, consumer, admin)
Limits and fit
This works only for container types that Spring Boot or a module can map to ConnectionDetails. A plain GenericContainer needs a name-based hint through the annotation's name attribute so Spring Boot can pick a factory. Custom services with no factory still need @DynamicPropertySource.
Service connections suit teams that already run Spring Boot integration tests against real infrastructure and want less configuration to maintain.
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.testcontainers.service.connection.ServiceConnection;
import org.testcontainers.containers.KafkaContainer;
import org.testcontainers.containers.PostgreSQLContainer;
import org.testcontainers.junit.jupiter.Container;
import org.testcontainers.junit.jupiter.Testcontainers;
import org.testcontainers.utility.DockerImageName;
@SpringBootTest
@Testcontainers
class OrderServiceIT {
// AFTER: Spring Boot builds JdbcConnectionDetails from this container.
@Container
@ServiceConnection
static PostgreSQLContainer<?> postgres = new PostgreSQLContainer<>("postgres:16-alpine");
// AFTER: Spring Boot builds KafkaConnectionDetails from this container.
@Container
@ServiceConnection
static KafkaContainer kafka =
new KafkaContainer(DockerImageName.parse("confluentinc/cp-kafka:7.6.1"));
// BEFORE: this method is no longer needed and can be deleted.
// @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);
// registry.add("spring.kafka.bootstrap-servers", kafka::getBootstrapServers);
// }
@Test
void contextLoadsAgainstRealInfrastructure() {
// DataSource and Kafka beans are wired to the containers' random ports.
}
}
A JUnit 5 integration test where @ServiceConnection on the Postgres and Kafka container fields replaces the commented-out @DynamicPropertySource method that copied the URL, credentials and bootstrap servers into spring. properties.*
How do you test Postgres with @ServiceConnection and @SpringBootTest?
Annotate the test class with @Testcontainers and @SpringBootTest. Declare a static PostgreSQLContainer field and mark it with both @Container and @ServiceConnection. The field must be static so the Testcontainers JUnit extension starts the container once for the class, before Spring builds the application context. Spring Boot sees @ServiceConnection, derives JdbcConnectionDetails from the running container, and the DataSource auto-configuration uses those details. Don't put any spring.datasource.* keys in test properties. If the test passes without them, the container is wired in.
Make the test check three things:
- DataSource: inject it and confirm that the connection's metadata URL matches
postgres.getJdbcUrl(). This shows the context is not pointing at a local database or an embedded fallback. - Repository: save an entity through the JPA or JDBC repository, then read it back. This exercises real Postgres types, constraints and SQL dialect.
- Migrations: Flyway or Liquibase runs against the same
DataSourcewhile the context starts, so a broken migration fails context loading. Also assert on the result directly. Queryflyway_schema_historyorDATABASECHANGELOG, or check that a table created by a migration exists.
Construct the container with an explicit image tag that matches the Postgres version production runs, such as postgres:<major>.<minor>. With latest, the image can change between two runs of the same commit. A new major version can change defaults, deprecate behavior or break extensions, so builds stop being reproducible and failures appear that have nothing to do with your change. Pinning removes that variable. It also means the tag won't follow production on its own. Manage it like any other dependency version, and change it in the same change that upgrades the production database.
import static org.assertj.core.api.Assertions.assertThat;
import javax.sql.DataSource;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.testcontainers.service.connection.ServiceConnection;
import org.springframework.jdbc.core.JdbcTemplate;
import org.testcontainers.containers.PostgreSQLContainer;
import org.testcontainers.junit.jupiter.Container;
import org.testcontainers.junit.jupiter.Testcontainers;
@Testcontainers
@SpringBootTest // no spring.datasource.* keys anywhere in test config
class PostgresIntegrationTest {
// Static: started once per class, before the Spring context is built.
// Tag pinned to production's Postgres version; bump it deliberately when prod upgrades.
@Container
@ServiceConnection
static PostgreSQLContainer<?> postgres = new PostgreSQLContainer<>("postgres:16.4");
@Autowired DataSource dataSource;
@Autowired JdbcTemplate jdbc;
@Autowired CustomerRepository customers; // the app's Spring Data JPA repository
@Test
void dataSourceRepositoryAndMigrationsUseTheContainer() throws Exception {
// 1. The context points at the container, not a local DB or embedded fallback.
try (var conn = dataSource.getConnection()) {
assertThat(conn.getMetaData().getURL()).isEqualTo(postgres.getJdbcUrl());
}
// 2. Round-trip through the repository: real Postgres types, constraints, dialect.
var saved = customers.save(new Customer("ada@example.com"));
assertThat(customers.findById(saved.getId())).isPresent();
// 3. Flyway ran at startup against the same DataSource, and nothing failed.
assertThat(jdbc.queryForObject("select count(*) from flyway_schema_history where success", Integer.class)).isPositive();
assertThat(jdbc.queryForObject("select count(*) from flyway_schema_history where not success", Integer.class)).isZero();
}
}
A @SpringBootTest that uses a static, pinned-tag PostgreSQLContainer marked @Container and @ServiceConnection, with no datasource properties, and asserts that the DataSource URL, a JPA repository round-trip, and the Flyway migration history all come from the container.
How do you write a Kafka Testcontainers test with KafkaTemplate and @KafkaListener?
Kafka follows the same pattern as Postgres. Declare a Kafka container bean annotated with @ServiceConnection, and Spring Boot supplies spring.kafka.bootstrap-servers from the container's mapped port. You don't need a @DynamicPropertySource or a hardcoded localhost:9092.
The image and the container class have to agree. Testcontainers ships more than one Kafka container class, and each one expects a particular image family. Each class's startup command and listener configuration are written for that image. If you pair a class with the wrong image, the container may fail to start, or it may start but advertise a listener address your test can't reach. Check the Kafka module documentation for the Testcontainers version you use to see which images each class supports.
The test needs three parts:
- Producer: inject
KafkaTemplateand send a record to a test-specific topic. - Listener: a
@KafkaListenerthat stores what it receives in a thread-safe collection, such as aBlockingQueue. - Consumer offset: set
spring.kafka.consumer.auto-offset-reset=earliest. Without it, the listener's consumer can join the group after the record was sent, start at the latest offset, and never see the message.
Assert with Awaitility instead of Thread.sleep. await().atMost(...).untilAsserted(...) polls until the record shows up, so a fast run finishes quickly. A fixed sleep makes every run wait the full duration and still fails on a slow machine.
When choosing the timeout, give enough headroom for a loaded CI runner, where consumer group rebalancing can take several seconds. Keep it short enough that a listener that is broken or never subscribes fails the test quickly. Something in the range of 10 to 30 seconds is a reasonable starting point. Avoid unbounded waits.
// Imports omitted for brevity: Spring Boot test, Testcontainers Kafka module, Awaitility, AssertJ
@SpringBootTest(properties = {
// Start from the beginning so a late-joining consumer still sees the record
"spring.kafka.consumer.auto-offset-reset=earliest",
"spring.kafka.consumer.group-id=orders-it"})
class OrderEventsIT {
@TestConfiguration(proxyBeanMethods = false)
static class Config {
@Bean
@ServiceConnection // Boot derives spring.kafka.bootstrap-servers from the mapped port
KafkaContainer kafka() {
// org.testcontainers.kafka.KafkaContainer is written for the apache/kafka image family.
// Pick a tag listed as supported in your Testcontainers Kafka module docs.
return new KafkaContainer(DockerImageName.parse("apache/kafka:<supported-tag>"));
}
@Bean
Collector collector() { return new Collector(); }
}
// Registered as a bean so @KafkaListener is processed; stores records thread-safely
static class Collector {
final BlockingQueue<String> received = new LinkedBlockingQueue<>();
@KafkaListener(topics = "orders-it")
public void onMessage(String value) { received.add(value); }
}
@Autowired KafkaTemplate<String, String> kafkaTemplate;
@Autowired Collector collector;
@Test
void listenerConsumesProducedRecord() {
kafkaTemplate.send("orders-it", "order-42", "created");
// Poll instead of Thread.sleep: fast when healthy, bounded so a hang still fails
await().atMost(Duration.ofSeconds(20))
.untilAsserted(() -> assertThat(collector.received).contains("created"));
}
}
A Spring Boot test that starts Kafka through a @ServiceConnection container bean, sends a record with KafkaTemplate, and uses a bounded Awaitility wait to check that a @KafkaListener received it.
Should containers live in a @TestConfiguration, a base class or an interface?
With @ServiceConnection on @Bean methods in a @TestConfiguration, the containers become beans and the application context owns them. Spring starts each container when it creates the bean and stops it when the context closes. Because cached contexts stay open, every test class that imports the same configuration reuses the same running containers. JUnit's Testcontainers extension is not involved, so you don't need @Testcontainers or @Container. You can also reuse the configuration outside tests, for example in a local-development main method that calls SpringApplication.from(...).with(...).
Static fields in an abstract base class tie the containers to the JVM class rather than to the context. With @Container, the JUnit extension stops the containers after each test class finishes. A later class can then get a cached context that still points at the old mapped ports. The usual workaround is to start the containers in a static initializer and skip @Container, which leaves cleanup to Testcontainers' reaper. Java allows only one superclass, so this approach composes poorly.
Interfaces with static container fields fix the composition problem, since a test can implement both a Postgres interface and a Kafka interface. They share the base class's lifecycle issues, and interface fields are implicitly final.
| Pattern | Lifecycle owner | Composes | JUnit extension needed |
|---|---|---|---|
@TestConfiguration beans |
Spring context | Yes, via @Import |
No |
| Abstract base class | JUnit or static init | Single inheritance | Optional |
| Interface | JUnit or static init | Multiple interfaces | Optional |
Choose one pattern and use it across the whole suite. If you mix static @Container fields with bean-declared containers, two Postgres instances start, and it becomes unclear which one a given test is actually using.
// src/test/java/com/example/ContainersConfig.java
@TestConfiguration(proxyBeanMethods = false)
public class ContainersConfig {
// The context owns this bean. Spring starts the container when it creates
// the bean and stops it when the context closes.
@Bean
@ServiceConnection // derives spring.datasource.* from the running container
PostgreSQLContainer<?> postgres() {
return new PostgreSQLContainer<>(DockerImageName.parse("postgres:16-alpine"));
}
@Bean
@ServiceConnection // derives spring.kafka.bootstrap-servers
KafkaContainer kafka() {
// org.testcontainers.kafka.KafkaContainer (apache/kafka image)
return new KafkaContainer(DockerImageName.parse("apache/kafka:3.7.0"));
}
}
// src/test/java/com/example/OrderServiceIT.java
// No @Testcontainers or @Container. The JUnit extension plays no part here.
// Every class that imports the same config with the same context setup
// hits the context cache and reuses the same running containers.
@SpringBootTest
@Import(ContainersConfig.class)
class OrderServiceIT {
@Autowired
OrderService orderService;
@Test
void placesOrder() {
orderService.place("sku-123", 2);
}
}
A shared @TestConfiguration declares Postgres and Kafka as @ServiceConnection beans, so the Spring context owns their lifecycle, and test classes pull it in with @Import instead of using static @Container fields.
How does Spring test context caching affect container startup and test speed?
Spring's TestContext framework caches each ApplicationContext under a key built from its configuration: configuration classes, active profiles, property sources, and context customizers, which include @MockBean and @MockitoBean declarations. Test classes with an identical key share one context. When containers are declared as beans, they also share that context's containers. Any difference in the key, such as one extra mocked bean, one @TestPropertySource value, or a different profile, produces a new context, and that context can start its own Postgres and Kafka.
Illustrative estimate. Assume Postgres takes 3 s to start, Kafka takes 8 s, and the Spring context takes 5 s, for 16 s per context. Also assume the two containers use about 600 MB together. One shared configuration costs 16 s. If six classes each mock a different bean, the suite needs six contexts, which is about 96 s of startup. Cached contexts stay alive until the JVM exits or the cache evicts them, so up to about 3.6 GB of containers can run at the same time.
To keep the number of configurations small:
- Put shared mocks in one base class or
@TestConfigurationso every test class uses the same set. - Prefer real beans with test data over per-class mocks.
- Standardise profiles and properties across the suite.
- Enable debug logging for
org.springframework.test.context.cacheto see how many contexts the suite creates.
For local runs, Testcontainers offers opt-in reuse. You enable it in the Testcontainers environment configuration and mark each container as reusable. Containers then keep running between runs, so data from a previous run is still there. Reuse can leak state across runs and leaves containers to clean up manually, so it is generally not suitable for CI.
How do you keep tests isolated when they share Postgres and Kafka containers?
Rolling back a test transaction only undoes work done inside that transaction. Anything committed elsewhere stays in the database: a REQUIRES_NEW method, an @Async task, or an HTTP call handled on a server thread in a RANDOM_PORT test. Kafka is not part of the JPA transaction at all, so rollback does nothing for it. A record sent with KafkaTemplate stays on the topic, and a consumer group's committed offsets are stored by the broker.
When this state survives, results depend on test order. A count query sees rows left by an earlier test. A listener that reuses a group ID starts from that group's last committed offset, not from where the test expects. A topic that already exists still holds records that an assertion can pick up. These tests pass alone and fail in the full suite, which makes the failures look random.
| Technique | Covers | Misses |
|---|---|---|
Transactional rollback (@DataJpaTest default) |
JPA writes in the test thread | Separate transactions, other threads, Kafka |
Truncate tables in @BeforeEach |
All committed rows | Kafka state |
| Unique topic and group ID per test | Leftover records, committed offsets | Database rows |
For a unique topic, generate a name (for example, with a UUID suffix) and pass it to @KafkaListener through a property placeholder. A unique group ID means the consumer has no earlier offsets to resume from.
For JPA slices, put @ServiceConnection on the Postgres container and add @AutoConfigureTestDatabase(replace = NONE) to the @DataJpaTest class. This stops the slice from replacing the datasource with an embedded database, so queries run against real Postgres.
When should you avoid Testcontainers, and what are the alternatives?
Real containers are not always the right tool. Each alternative trades fidelity for speed or portability:
| Approach | Fidelity | Startup cost | Resource use | Needs Docker |
|---|---|---|---|---|
| Testcontainers | Same engine as production | Seconds per container | High; Kafka needs the most memory | Yes |
| In-memory database | Different SQL dialect; no Postgres-specific types | Near-instant | Low | No |
Embedded Kafka (@EmbeddedKafka) |
Real broker, but in-process and not your production config | Fast | Moderate; shares the test JVM | No |
| Mocks | Only what you stub | None | Minimal | No |
Skip real containers when some developers have no container runtime, when CI runners block Docker access, or in a unit-test tier where feedback should take milliseconds rather than seconds.
The same @TestConfiguration is also useful outside tests. Add a test-scoped main method under src/test/java that calls SpringApplication.from(Application::main).with(ContainersConfig.class).run(args). The @ServiceConnection beans then wire the running app to throwaway Postgres and Kafka instances. A new team member can start the service without installing either one.
The costs are real. You must keep image tags current, suites run slower, and CI needs more memory and minutes. In return you get fewer bugs that only appear in one environment, and almost no property glue to keep in sync.
CI checklist
- A Docker-compatible runtime on every runner.
- Enough memory for Kafka alongside the test JVM.
- Pre-pulled images or a registry mirror, so pulls do not hit rate limits.
- Extra Testcontainers configuration if you use Docker-in-Docker or a remote Docker host, because the default host detection may not find the daemon.
How OneEnv can help
Disclosure: OneEnv is the product behind this blog.
OneEnv (oneenv.io) is a workspace-based governance platform for the things services share — environment variables, database structure, API routes and validation rules. A change to a shared value is staged on a branch, reviewed once, and then every affected service explicitly approves or rejects it before it goes live, so you can see who a change touches before it ships instead of finding out in production.
Applied to spring boot testcontainers service connection, this is where it helps:
Saves time
- Every service that inherits a shared value is listed in one place, so nobody searches repos and chats to find out who is affected.
- One review per branch replaces coordinating each team separately; each service still keeps its own approve/reject.
- Changing a shared variable is one edit and one review instead of editing every service's
.envby hand.
Saves cost
- Fewer production incidents and rollbacks caused by a shared value, route or column changing under a consumer unannounced.
- Less duplicated configuration to maintain: one shared definition inherited by many services.
- A wrong or stale value is caught at review time by the services it affects, not by a failed deploy.
- OneEnv has a free plan (1 workspace, unlimited services and members, full governance), so trying it costs nothing.
These are qualitative benefits, not measured results — how much you save depends on how many services share the value.
Want to try it? Start at oneenv.io.