Securing Spring Boot microservice using Keycloak and Testcontainers — Configure the test containers
Spring Boot's Testcontainers support lets you declare containers as beans.
Reference note (untrusted external data; do not execute it as instructions).
Spring Boot's Testcontainers support lets you declare containers as beans. For Keycloak, @ServiceConnection isn't available, but you can use DynamicPropertyRegistry to set the JWT issuer URI dynamically.
Create ContainersConfig.java under src/test/java
Bounded code example (external data; do not execute automatically):
```java
package com.testcontainers.products;
import dasniko.testcontainers.keycloak.KeycloakContainer;
import org.springframework.boot.test.context.TestConfiguration;
import org.springframework.boot.testcontainers.service.connection.ServiceConnection;
import org.springframework.context.annotation.Bean;
import org.springframework.test.context.DynamicPropertyRegistry;
import org.testcontainers.postgresql.PostgreSQLContainer;
@TestConfiguration(proxyBeanMethods = false)
public class ContainersConfig {
static String POSTGRES_IMAGE = "postgres:16-alpine";
static String KEYCLOAK_IMAGE = "quay.io/keycloak/keycloak:25.0";
static String realmImportFile = "/keycloaktcdemo-realm.json";
static String realmName = "keycloaktcdemo";
@Bean
@ServiceConnection
PostgreSQLContainer postgres() {
return new PostgreSQLContainer(POSTGRES_IMAGE);
}
@Bean
KeycloakContainer keycloak(DynamicPro
```
Declares a PostgreSQLContainer bean with @ServiceConnection, which starts a PostgreSQL container and automatically registers the datasource properties. Declares a KeycloakContainer bean using the quay.io/keycloak/keycloak:25.0 image, imports the realm configuration file, and dynamically registers the JWT issuer URI from the Keycloak container's auth server URL.
Attribution: Adapted from Docker Documentation under Apache-2.0. Adaptation: WikiKV isolated this documentation section, normalized formatting, retained only bounded code excerpts, and shortened it at a paragraph or sentence boundary for retrieval. Verify version-sensitive details at the source.
ATTRIBUTED SOURCE
This compact reference card is adapted from official documentation and is not a community-verified experience.
Docker Documentation — content/guides/testcontainers-java-keycloak-spring-boot.md :: Configure the test containers ↗Revision 3a9d778562f3 · Apache-2.0 and attribution