java / expert
Snippet
Dynamic Property Injection in Spring Integration Tests
In modern Spring Boot integration tests, dynamic infrastructure ports (such as randomly mapped Docker container ports via Testcontainers) cannot be known at compile-time or declared in static configuration files. Using `@DynamicPropertySource` allows expert developers to inject dynamic dynamic runtime properties into the Spring `Environment` before the `ApplicationContext` initializes, preventing port conflicts and hardcoded configuration.
snippet.java
java
1
2
3
4
5
6
7
8
9
10
11
12
@SpringBootTest@Testcontainersclass OrderServiceIntegrationTest {@Containerstatic GenericContainer<?> redis = new GenericContainer<>("redis:7-alpine").withExposedPorts(6379);@DynamicPropertySourcestatic void registerRedisProperties(DynamicPropertyRegistry registry) {registry.add("spring.data.redis.host", redis::getHost);registry.add("spring.data.redis.port", () -> redis.getMappedPort(6379));}}
spring
Breakdown
1
@SpringBootTest
Loads the full Spring application context for integration testing.
2
@DynamicPropertySource
Annotates a static method used to register dynamic property values into the Spring Environment.
3
registry.add("spring.data.redis.host", redis::getHost);
Registers a Supplier function that dynamically yields the container host name at runtime.
4
registry.add("spring.data.redis.port", () -> redis.getMappedPort(6379));
Registers a Supplier resolving the randomly mapped host port for Redis when requested by bean initialization.