Explain the bean life cycle in Spring Framework

The following is the sequence of a bean life cycle in Spring:

  • Instantiate: First, the Spring container finds the bean’s definition from the XML file and instantiates the bean.
  • Populate Properties: Using the dependency injection, Spring populates all of the properties as specified in the bean definition.
  • Set Bean Name: If the bean implements the BeanNameAware interface, then Spring passes the bean’s ID to the setBeanName() method.
  • Set Bean Factory: If the bean implements the BeanFactoryAware interface, then Spring passes the bean factory to the setBeanFactory() method.
  • Pre-initialization: It is also called the post-process of the bean. If there are any BeanPostProcessors associated with the bean, then Spring calls the postProcesserBeforeInitialization() method.
  • Initialize Beans: If the bean implements IntializingBean, its afterPropertySet() method is called. If the bean has the init method declaration, the specified initialization method is called.
  • Post Initialization: If there are any BeanPostProcessors associated with the bean, their postProcessAfterInitialization() methods will be called.
  • Ready to Use: Now, the bean is ready to use by the application.
  • Destroy: If the bean implements DisposableBean, it will call the destroy() method.