java / intermediate
Snippet
Configuring Dynamic Environment Properties in Spring Boot Integration Tests
When running integration tests against external test infrastructure such as dynamic containers, target ports and hostnames are not known ahead of time. The `@DynamicPropertySource` annotation allows developers to supply dynamic configuration values to the Spring `Environment` using functional `Supplier` instances. This mechanism executes before the application context is refreshed, ensuring that downstream beans receive dynamically evaluated connection strings without requiring hardcoded property overrides.
snippet.java
java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)class PaymentGatewayIntegrationTest {static final GenericContainer<?> mockServer =new GenericContainer<>("mockserver/mockserver:latest").withExposedPorts(1080);static {mockServer.start();}@DynamicPropertySourcestatic void configureDynamicProperties(DynamicPropertyRegistry registry) {registry.add("payment.gateway.url",() -> "http://" + mockServer.getHost() + ":" + mockServer.getMappedPort(1080));}@Testvoid shouldProcessPaymentAgainstDynamicEndpoint() {// Test execution against the dynamic endpoint}}
spring
Breakdown
1
@DynamicPropertySource
Registers a static method that injects dynamic properties into the Spring Environment before context startup.
2
static void configureDynamicProperties(DynamicPropertyRegistry registry)
Static callback receiving the registry where name-to-Supplier key-value pairs are bound.
3
registry.add("payment.gateway.url", () -> "http://" + mockServer.getHost() + ":" + mockServer.getMappedPort(1080));
Lazily evaluates and injects the container's randomized mapped host and port as a runtime property.