There are various Bean Life Cycle interfaces and methods that will be called by the IOC Container.
- The lifecycle of a bean within a Spring Application Context differs only slightly from that of a bean within a bean factory.
- If the bean implements the ApplicationContext, the setApplicationContext is called.
There are following step perform in spring Bean Life Cycle :-
- Instantiate : Spring instantiates the bean A Spring bean needs to be instantiated when the container starts, based on Java or XML bean definition.
- Populate Properties : Now Spring injects the beans properties.
- Set Bean Name : If the bean implements BeanNameAware, Spring passes the bean’s ID to setBeanName() method.
- SetBean Factory : If the bean implements BeanNameAware, Spring passes the bean factory to setBeanFactory.
- Before Initialisation : If there are any BeanPostProcessors, Spring calls their postProcessBeforeInitialization() method.
- Initialize beans : If the bean implements Initializingbean, its afterPropertiesSet() method will be called. If the bean has a custom init method declared, the specified initialization method will be called.
- After Initialization : If there are any BeanPostProcesssors, Spring calls their postProcessAfterInitialization() method.
- Bean is ready to use : At this point the bean is ready for use.
- Destroy Bean : If the bean implements DisposableBean, its destroy() method will be called.