How to Replace a Bean During Startup In Spring
There are circumstances in that we need to override a bean's methods which is from an external package but keep the same bean name. We can achieve this by replacing bean definition during application startup using BeanFactoryPostProcessor
.
BeanFactoryPostProcessor
A BeanFactoryPostProcessor
may interact with and modify bean definitions, but never bean instances. Allows for custom modification of an application context's bean definitions, adapting the bean property values of the context's underlying bean factory. Application contexts can auto-detect BeanFactoryPostProcessor beans in their bean definitions and apply them before any other beans get created.
Example
Following is the service from external packages, and we need to replace it:
In order to replace it, we create AntBeanFactoryPostProcessor
that implements BeanFactoryPostProcessor
. We first remove the original bean definition, and register with new definition.
Then we can check if the replacement is valid:
We would get the following result:
----- BeanFactoryPostProcessor register bean: ant
ant from BeanFactoryPostProcessor
Recommendation
-
Four ways to dynamically register a bean
- GenericBeanDefinition
- BeanDefinitionBuilder
- BeanFactoryPostProcessor
- BeanDefinitionRegistryPostProcessor