BeanFactoryPostProcessor and BeanPostProcessor in lifecycle events
I was trying to understand the difference between BeanFactoryPostProcessor
and BeanPostProcessor
.
I understood that BeanFactoryPostProcessor
operates on bean definition i.e. before the bean instance is getting created it gets executed and BeanPostProcessor
gets executed after bean is instantiated and lifecycle events are called.
Does this mean BeanFactoryPostProcessor
is not a part of spring lifecycle events as it's called before instantiation while BeanPostProcessor
is the part of Spring lifecycle events? Kindly verify if my understanding is right.
Solution 1:
BeanFactoryPostProcessor
is an interface and beans that implement it are actually beans that undergo the Spring lifecycle (Example below) but these beans don't take part of the other declared beans' lifecycle.
public class CustomBeanFactory implements BeanFactoryPostProcessor {
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
for (String beanName : beanFactory.getBeanDefinitionNames()) {
BeanDefinition beanDefinition = beanFactory.getBeanDefinition(beanName);
// Manipulate the beanDefiniton or whatever you need to do
}
}
}
The differences about BeanFactoryPostProcessor
and BeanPostProcessor
:
- A bean implementing
BeanFactoryPostProcessor
is called when all bean definitions will have been loaded, but no beans will have been instantiated yet. This allows for overriding or adding properties even to eager-initializing beans. This will let you have access to all the beans that you have defined in XML or that are annotated (scanned via component-scan). - A bean implementing
BeanPostProcessor
operate on bean (or object) instances which means that when the Spring IoC container instantiates a bean instance then BeanPostProcessor interfaces do their work. -
BeanFactoryPostProcessor
implementations are "called" during startup of the Spring context after all bean definitions will have been loaded whileBeanPostProcessor
are "called" when the Spring IoC container instantiates a bean (i.e. during the startup for all the singleton and on demand for the proptotypes one)
Solution 2:
Here is a flow diagram that might help to understand the spring bean initialisation life cycle.
As we can see, the implementation of theBeanFactoryPostProcessor is executed before any spring bean instantiation, contrary to the BeanPostprocessor, where the implemented method will be executed only when the bean is instantiated.
The source image is from the Spring 5 Design Patterns Book.
I pick the explanation from the book:
After loading the bean definitions from all styles of configurations, BeanFactoryPostProcessor comes into the picture to modify the definition of some beans, and then the container instantiates the beans. Finally, BeanPostProcessor works on the beans, and it can modify and change the bean object. This is the initialization phase.