Spring Bean - Life Cycle

This is mainly asked in interviews so need to prepare properly concept and purpose of the same.

Spring framework is based on IOC so we call it as IOC container also So Spring beans reside inside the IOC container. Spring beans are nothing but Plain old java object (POJO).

Following steps explain their life cycle inside the container.

  1. The container will look the bean definition inside configuration file (e.g. bean.xml).

  2. Using reflection container will create the object and if any property is defined inside the bean definition then it will also be set.

  3. If the bean implements the BeanNameAware interface, the factory calls setBeanName() passing the bean’s ID.

  4. If the bean implements the BeanFactoryAware interface, the factory calls setBeanFactory(), passing an instance of itself.

  5. If there are any BeanPostProcessors associated with the bean, their post- ProcessBeforeInitialization() methods will be called before the properties for the Bean are set.

  6. If an init() method is specified for the bean, it will be called.

  7. If the Bean class implements the DisposableBean interface, then the method destroy() will be called when the Application no longer needs the bean reference.

  8. If the Bean definition in the Configuration file contains a 'destroy-method' attribute, then the corresponding method definition in the Bean class will be called.


Try below program to understand flow: