Spring Bean Life Cycle

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.
spring bean life cycle

There are following step perform in spring Bean Life Cycle :-

  1. Instantiate : Spring instantiates the bean A Spring bean needs to be instantiated when the container starts, based on Java or XML bean definition.
  2. Populate Properties : Now Spring injects the beans properties.
  3. Set Bean Name : If the bean implements BeanNameAware, Spring passes the bean’s ID to  setBeanName() method.
  4. SetBean Factory : If the bean implements BeanNameAware, Spring passes the bean factory to setBeanFactory.
  5. Before Initialisation : If there are any BeanPostProcessors, Spring calls their postProcessBeforeInitialization() method.
  6. 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.
  7. After Initialization : If there are any BeanPostProcesssors, Spring calls their postProcessAfterInitialization() method.
  8. Bean is ready to use : At this point the bean is ready for use.
  9. Destroy Bean : If the bean implements DisposableBean, its destroy() method will be called.