spring-projects / spring-framework

Spring Framework
https://spring.io/projects/spring-framework
Apache License 2.0
55.48k stars 37.71k forks source link

Register `DynamicPropertyRegistry` as a singleton bean in a test's `ApplicationContext` #32271

Closed sbrannen closed 4 weeks ago

sbrannen commented 4 months ago

Overview

DynamicPropertyRegistry was introduced in conjunction with the @DynamicPropertySource support in the TestContext framework. For such use cases, a static method within a test class must be annotated with @DynamicPropertySource, and a DynamicPropertyRegistry will be supplied as a method argument.

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.

In light of that, we will register DynamicPropertyRegistry as a singleton bean in a test's ApplicationContext. That will allow DynamicPropertyRegistry to be autowired into a @Configuration class or supplied to a @Bean method as a method argument as shown in the following example.

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

In order to address the @DependsOn concern raised in #32209, we are considering allowing @DynamicPropertySource to be applied to @Bean methods to indicate that the corresponding bean should be eagerly initialized within the test's ApplicationContext.

Related Issues

sbrannen commented 4 months ago

A proof of concept can be viewed in the following feature branch.

https://github.com/spring-projects/spring-framework/compare/main...sbrannen:spring-framework:issues/gh-32209-register-DynamicPropertyRegistry-as-bean