Integration testing with Testcontainers and @ServiceConnection
Wire PostgreSQL and Redis Testcontainers in Spring Boot 3.1 using @ServiceConnection, singleton containers, container reuse, and local TestApplication.
After H2’s PostgreSQL compatibility mode missed a real query bug, I moved our integration tests onto real PostgreSQL and Redis containers. Here is how I removed manual property boilerplate with Spring Boot 3.1’s
@ServiceConnection, set up singleton containers, and wired a localTestApplication.
Tested with Spring Boot 3.1.5, Testcontainers 1.19.1, Kotlin 1.9.10, PostgreSQL 16, Redis 7, and Docker Desktop.
Background
Our team project originally ran its integration tests against H2 using jdbc:h2:mem:testdb;MODE=PostgreSQL. Everything stayed green until we added a native query using a jsonb column and the ->> operator. The test schema drifted from the production schema, and a query that passed locally behaved differently once deployed. That failure made one thing clear: if your test database isn’t the same engine as production, green tests give you false confidence.
Testcontainers solves that gap by starting real Docker containers during tests and cleaning them up when the JVM exits. Through Spring Boot 3.0, however, you still had to copy each container’s random host port into spring.datasource.url and similar keys via @DynamicPropertySource. Spring Boot 3.1 introduced @ServiceConnection, which wires those connections automatically without manual property registration.
| Approach | Connection wiring | Strengths | When not to use |
|---|---|---|---|
| H2 compatibility mode | Fixed in application.yml | Fastest startup; no Docker required | Queries using DB-specific syntax or column types |
@DynamicPropertySource | Register property keys manually | Works with any library or custom container | Typos or renamed keys aren’t caught at compile time |
@ServiceConnection | Auto-registers ConnectionDetails beans | Zero property boilerplate; type-safe | Containers not yet on Spring Boot’s supported list |
| Spring Boot Docker Compose | Driven by compose.yaml | Shares config with local development | Tests that need isolated, ephemeral containers |
Container-backed tests aren’t right for every case either. If your CI runner doesn’t have Docker access, or if you’re only verifying pure domain calculations, spinning up containers adds seconds of overhead for zero benefit. Keep unit tests and test slices as your fast inner loop, and reserve Testcontainers for integration tests that genuinely exercise real database or cache behavior.
Project setup
Spring Boot 3.1.5 manages Testcontainers 1.18.3 by default. I overrode the testcontainers.version property in build.gradle.kts to use 1.19.1, which was the latest release at the time.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
// build.gradle.kts
plugins {
id("org.springframework.boot") version "3.1.5"
id("io.spring.dependency-management") version "1.1.3"
kotlin("jvm") version "1.9.10"
kotlin("plugin.spring") version "1.9.10"
kotlin("plugin.jpa") version "1.9.10"
}
extra["testcontainers.version"] = "1.19.1"
dependencies {
implementation("org.springframework.boot:spring-boot-starter-data-jpa")
implementation("org.springframework.boot:spring-boot-starter-data-redis")
implementation("org.springframework.boot:spring-boot-starter-web")
implementation("org.jetbrains.kotlin:kotlin-reflect")
runtimeOnly("org.postgresql:postgresql")
testImplementation("org.springframework.boot:spring-boot-starter-test")
testImplementation("org.springframework.boot:spring-boot-testcontainers")
testImplementation("org.testcontainers:junit-jupiter")
testImplementation("org.testcontainers:postgresql")
}
tasks.withType<Test> {
useJUnitPlatform()
}
Step 1. Singleton containers with @ServiceConnection
If you follow the basic JUnit 5 docs and pair @Testcontainers with @Container, Testcontainers stops and restarts the containers for every test class. Once you have a dozen integration test classes, those repeated startups add up fast. Instead, I use the singleton container pattern: start PostgreSQL and Redis once inside an abstract base class’s companion object and let Ryuk clean them up when the test JVM finishes.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
// src/test/kotlin/com/example/studyroom/support/IntegrationTestSupport.kt
package com.example.studyroom.support
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.boot.testcontainers.service.connection.ServiceConnection
import org.testcontainers.containers.GenericContainer
import org.testcontainers.containers.PostgreSQLContainer
import org.testcontainers.utility.DockerImageName
@SpringBootTest
abstract class IntegrationTestSupport {
companion object {
@JvmStatic
@ServiceConnection
val postgres = PostgreSQLContainer("postgres:16-alpine")
@JvmStatic
@ServiceConnection(name = "redis")
val redis: GenericContainer<*> = GenericContainer(DockerImageName.parse("redis:7-alpine"))
.withExposedPorts(6379)
init {
postgres.start()
redis.start()
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// src/test/kotlin/com/example/studyroom/reservation/ReservationIntegrationTest.kt
package com.example.studyroom.reservation
import com.example.studyroom.support.IntegrationTestSupport
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Test
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.data.redis.core.StringRedisTemplate
import org.springframework.jdbc.core.JdbcTemplate
class ReservationIntegrationTest(
@Autowired val jdbcTemplate: JdbcTemplate,
@Autowired val redisTemplate: StringRedisTemplate,
) : IntegrationTestSupport() {
@Test
fun `connects to real PostgreSQL and Redis containers`() {
val version = jdbcTemplate.queryForObject("select version()", String::class.java)
redisTemplate.opsForValue().set("ping", "pong")
assertThat(version).contains("PostgreSQL 16")
assertThat(redisTemplate.opsForValue().get("ping")).isEqualTo("pong")
}
}
Notice the difference between the two annotations. Spring Boot can infer PostgreSQL directly from the PostgreSQLContainer class type. Redis doesn’t have a dedicated Testcontainers module here, so when using GenericContainer, you must pass name = "redis" so Spring Boot knows which ConnectionDetails factory to pick.
How @ServiceConnection works vs. @DynamicPropertySource
@ServiceConnection doesn’t work by overwriting environment properties. Instead, Spring Boot 3.1 introduced ConnectionDetails abstractions—such as JdbcConnectionDetails and RedisConnectionDetails—and updated auto-configurations to prefer those beans over spring.datasource.* or spring.data.redis.* properties whenever present.
flowchart TD
A["ServiceConnectionContextCustomizerFactory"] --> B["Scan static fields for @ServiceConnection"]
B --> C["Match ContainerConnectionDetailsFactory"]
C --> D["Register JdbcConnectionDetails bean"]
D --> E["DataSourceAutoConfiguration uses bean first"]
Looking one layer deeper, ServiceConnectionContextCustomizerFactory scans the test class and its superclasses for @ServiceConnection fields. If a field isn’t static, startup fails with @ServiceConnection field 'postgres' must be static. In Kotlin, properties inside a companion object compile to static fields on the enclosing class, which is why the setup above works. Once discovered, each container is matched by type or name to a ContainerConnectionDetailsFactory, which registers the ConnectionDetails bean and resolves the host and mapped port after the container starts.
For comparison, here is what the same setup required with @DynamicPropertySource before Spring Boot 3.1:
1
2
3
4
5
6
7
8
9
10
// Pre-Spring Boot 3.1 approach for comparison
@JvmStatic
@DynamicPropertySource
fun registerProperties(registry: DynamicPropertyRegistry) {
registry.add("spring.datasource.url", postgres::getJdbcUrl)
registry.add("spring.datasource.username", postgres::getUsername)
registry.add("spring.datasource.password", postgres::getPassword)
registry.add("spring.data.redis.host", redis::getHost)
registry.add("spring.data.redis.port") { redis.getMappedPort(6379) }
}
Hardcoding property keys breaks quietly across major upgrades—for example, Spring Boot 3 renamed the Redis prefix from spring.redis to spring.data.redis. @ServiceConnection removes that coupling, so I default to it for every supported container.
Keep in mind that the container configuration also becomes part of the Spring TestContext cache key via ContextCustomizer. Having every integration test extend the same IntegrationTestSupport base class ensures Spring boots one ApplicationContext and reuses it across the suite. I covered how TestContext cache keys work in detail in Spring Boot test slices and ApplicationContext caching.
Step 2. Local development with TestApplication and container reuse
Spring Boot 3.1 also added support for launching your application from a main function on the test classpath. By declaring the same containers as @Bean methods inside a @TestConfiguration, you can run your local development server against the exact same database and Redis images used in integration tests.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
// src/test/kotlin/com/example/studyroom/TestStudyRoomApplication.kt
package com.example.studyroom
import org.springframework.boot.fromApplication
import org.springframework.boot.test.context.TestConfiguration
import org.springframework.boot.testcontainers.service.connection.ServiceConnection
import org.springframework.boot.with
import org.springframework.context.annotation.Bean
import org.testcontainers.containers.GenericContainer
import org.testcontainers.containers.PostgreSQLContainer
import org.testcontainers.utility.DockerImageName
@TestConfiguration(proxyBeanMethods = false)
class LocalContainersConfig {
@Bean
@ServiceConnection
fun postgres(): PostgreSQLContainer<*> =
PostgreSQLContainer("postgres:16-alpine").withReuse(true)
@Bean
@ServiceConnection(name = "redis")
fun redis(): GenericContainer<*> =
GenericContainer(DockerImageName.parse("redis:7-alpine")).withExposedPorts(6379)
}
fun main(args: Array<String>) {
fromApplication<StudyRoomApplication>().with(LocalContainersConfig::class).run(*args)
}
Running ./gradlew bootTestRun starts the container beans first and connects the Spring Boot app to them automatically. For withReuse(true) to take effect, you must also add testcontainers.reuse.enable=true to ~/.testcontainers.properties. With reuse enabled, subsequent restarts attach to the already-running container instead of booting a new one, which cuts local startup time down to a couple of seconds.
Testcontainers’ Ryuk sidecar does not clean up reusable containers, so you have to stop and remove them manually via
docker ps. Because data persists across restarts, reuse can also break test isolation. I enablewithReuse(true)only for localbootTestRundevelopment and leave it off in CI and automated test code. Also, never combine@Containerwith the singleton container pattern—@Containerstops the container at the end of the first test class and breaks connections for every class that runs after it.
Summary
Moving integration tests to real PostgreSQL and Redis containers cost only a few seconds of startup time, and @ServiceConnection eliminated the property wiring boilerplate. Here is the checklist I verify before rolling this setup into a project:
- Confirm that the suite exercises DB-specific syntax or types that H2 can’t reliably validate.
- Declare container fields as static properties inside a
companion object. - Specify
@ServiceConnection(name = ...)whenever usingGenericContainer. - Have all integration test classes inherit from a single base class to share one
ApplicationContext. - Restrict
withReuse(true)to local development (bootTestRun), never CI or automated test suites.