Annotation Interface DynamicPropertySource


@Target(METHOD) @Retention(RUNTIME) @Documented public @interface DynamicPropertySource
Method-level annotation for integration tests that need to add properties with dynamic values to the Environment's set of PropertySources.

This annotation and its supporting infrastructure were originally designed to allow properties from Testcontainers based tests to be exposed easily to Spring integration tests. However, this feature may also be used with any form of external resource whose lifecycle is maintained outside the test's ApplicationContext.

Methods annotated with @DynamicPropertySource must be static and must have a single DynamicPropertyRegistry argument which is used to add name-value pairs to the Environment's set of PropertySources. Values are dynamic and provided via a Supplier which is only invoked when the property is resolved. Typically, method references are used to supply values, as in the example below.

As of Spring Framework 5.3.2, dynamic properties from methods annotated with @DynamicPropertySource will be inherited from enclosing test classes, analogous to inheritance from superclasses and interfaces. See @NestedTestConfiguration for details.

NOTE: if you use @DynamicPropertySource in a base class and discover that tests in subclasses fail because the dynamic properties change between subclasses, you may need to annotate your base class with @DirtiesContext to ensure that each subclass gets its own ApplicationContext with the correct dynamic properties.

Precedence

Dynamic properties have higher precedence than those loaded from @TestPropertySource, the operating system's environment, Java system properties, or property sources added by the application declaratively by using @PropertySource or programmatically. Thus, dynamic properties can be used to selectively override properties loaded via @TestPropertySource, system property sources, and application property sources.

Example

 @SpringJUnitConfig(...)
 @Testcontainers
 class ExampleIntegrationTests {

     @Container
     static RedisContainer redis = new RedisContainer();

     // ...

     @DynamicPropertySource
     static void redisProperties(DynamicPropertyRegistry registry) {
         registry.add("redis.host", redis::getContainerIpAddress);
         registry.add("redis.port", redis::getMappedPort);
     }

 }
Since:
5.2.5
Author:
Phillip Webb, Sam Brannen
See Also: