spring-framework/framework-docs/modules/ROOT/pages/testing
Sam Brannen 6cdb34410b Register DynamicPropertyRegistry as singleton bean in test ApplicationContext
Prior to this commit, DynamicPropertyRegistry could only be used with a
static @⁠DynamicPropertySource method in an integration test class;
however, it can also be useful to be able to register a "dynamic
property" from within a test's ApplicationContext -- for example, in a
@⁠Bean method in a @⁠Configuration class that is specific to testing
scenarios.

To support such use cases, this commit updates the dynamic property
source infrastructure so that a DynamicPropertyRegistry is always
registered as a singleton bean in a test's ApplicationContext. This
allows DynamicPropertyRegistry to be autowired into a @⁠Configuration
class or supplied to a @⁠Bean method as an argument as shown in the
following example.

@⁠Bean
@⁠DynamicPropertySource
ApiServer apiServer(DynamicPropertyRegistry registry) {
	ApiServer apiServer = new ApiServer();
	registry.add("api.url", apiServer::getUrl);
	return apiServer;
}

Note that the use of @⁠DynamicPropertySource on the @⁠Bean method is
optional and results in the corresponding bean being eagerly
initialized so that other singleton beans in the context can be given
access to the dynamic properties sourced from that bean when those
other beans are initialized.

Side note: DynamicPropertySourceBeanInitializer temporarily implements
LoadTimeWeaverAware since doing so is currently the only way to have a
component eagerly initialized before the
ConfigurableListableBeanFactory.preInstantiateSingletons() phase.
However, we plan to introduce a first-class callback to support such
use cases in the future.

Closes gh-32271
2024-05-15 17:09:03 +02:00
..
annotations Use by-type semantics in bean overriding if no explicit name is provided 2024-05-14 16:42:11 +02:00
spring-mvc-test-framework Merge branch '6.1.x' 2024-05-13 11:41:22 +01:00
testcontext-framework Register DynamicPropertyRegistry as singleton bean in test ApplicationContext 2024-05-15 17:09:03 +02:00
annotations.adoc
appendix.adoc
integration.adoc
introduction.adoc
resources.adoc Extract recurring asciidoc links to attributes, cleanup old doc files 2023-11-21 15:59:24 +01:00
spring-mvc-test-client.adoc Extract recurring asciidoc links to attributes, cleanup old doc files 2023-11-21 15:59:24 +01:00
spring-mvc-test-framework.adoc
support-jdbc.adoc
testcontext-framework.adoc
unit.adoc Extract recurring asciidoc links to attributes, cleanup old doc files 2023-11-21 15:59:24 +01:00
webtestclient.adoc Use expectBody<Person>() in WebTestClient documentation 2024-05-02 11:07:36 +02:00