Functional bean registration is a feature that was added to Spring Framework 5. This feature allows to create and register beans in the application context without use of reflection API and also can boost up application startup time.
Beans can be defined and registered functionally in classes implementing ApplicationContextInitializer interface.
Beans registration
A bean definition can be registered in the application context by calling registerBean method of the GenericApplicationContext class. This method accepts following arguments:
- Bean name; can be null
- Bean type, the only required argument; cannot be null
- Supplier instance, that instantiates and configures the bean object if additional actions are needed; can be null
- BeanDefinitionCustomizer instances, that configures the bean if needed; can be null
Here you can see an example of two beans’ functional registration:
Pay attention that a bean type can be an interface or a class.
Using context initializers
ApplicationContextInitializer implementations must be manually registered in the application context in difference from classes annotated by Spring annotations such, as @Configuration or @Component.
Also multiple instances of ApplicationContextInitializer can be used at the same time. It allows to separate beans definitions by functionality or to use types with limited visibility.
Context initializers can be defined in META-INF/spring.factories:
This file is used in integration tests also. Multiple context initializers definitions must be divided by a comma.
Context initializers can be registered in SpringApplicationBuilder also:
But in this case context initializers must be manually registered for integration tests: