Interface DynamicPropertyRegistrar
- Functional Interface:
- This is a functional interface and can therefore be used as the assignment target for a lambda expression or method reference.
Environment
via a DynamicPropertyRegistry
.
Any bean in a test's ApplicationContext
that implements the
DynamicPropertyRegistrar
interface will be automatically detected and
eagerly initialized before the singleton pre-instantiation phase, and the
accept(org.springframework.test.context.DynamicPropertyRegistry)
methods of such beans will be invoked with a
DynamicPropertyRegistry
that performs the actual dynamic property
registration on behalf of the registrar.
This is an alternative to implementing
@DynamicPropertySource
methods in integration
test classes and supports additional use cases that are not possible with a
@DynamicPropertySource
method. For example, since a
DynamicPropertyRegistrar
is itself a bean in the ApplicationContext
,
it can interact with other beans in the context and register dynamic properties
that are sourced from those beans. Note, however, that any interaction with
other beans results in eager initialization of those other beans and their
dependencies.
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
The following example demonstrates how to implement a
DynamicPropertyRegistrar
as a lambda expression that registers a
dynamic property for the ApiServer
bean. Other beans in the
ApplicationContext
can access the api.url
property which is
dynamically retrieved from the ApiServer
bean — for example,
via @Value("${api.url}")
.
@Configuration class TestConfig { @Bean ApiServer apiServer() { return new ApiServer(); } @Bean DynamicPropertyRegistrar apiPropertiesRegistrar(ApiServer apiServer) { return registry -> registry.add("api.url", apiServer::getUrl); } }
- Since:
- 6.2
- Author:
- Sam Brannen
- See Also:
-
Method Summary
Modifier and TypeMethodDescriptionvoid
accept
(DynamicPropertyRegistry registry) Register dynamic properties in the supplied registry.
-
Method Details
-
accept
Register dynamic properties in the supplied registry.
-