Spring Bean Lifecycle

  1. Instantiate a bean.
  2. Configure the instantiated bean according to the Spring context.
  3. If this bean implements the BeanNameAware interface, then call its implemented setBeanName(String) method; the parameter passed is the ID value of the bean in the Spring configuration file.
  4. If this bean implements the BeanFactoryAware interface, then call its implemented setBeanFactory(BeanFactory) method; the parameter passed is the Spring factory itself.
  5. If this bean implements the ApplicationContextAware interface, then call the setApplicationContext(ApplicationContext) method; the parameter passed to it is the Spring context.
  6. If a bean associates with the BeanPostProcessor interface, then call its implemented postProcessBeforeInitialization(Object obj, String s) method; this method is called before the bean initialization and is commonly used for defining pre-initialization work on beans, such as initializing system caches.
  7. If an init-method attribute is configured in the Spring configuration file for a bean, its configured initialization method will be automatically invoked.
// Example: Configuring init-method in XML or annotations
@Bean(initMethod = "initializeCache")
public MyBean myBean() { ... }
  1. If a certain bean associates with the BeanPostProcessor interface, then call the postProcessAfterInitialization(Object obj, String s) method; at this point, the initialization work for the bean is completed, and the application can begin to use the bean instance.

  2. When a bean is no longer needed, it will be cleaned up during the cleanup phase. If the bean implements the DisposableBean interface, then Spring will call its implemented class's destroy() method before exiting.

  3. If an init-method attribute or destroy-method attribute (note: context specifies "destroy-method") is configured in the Spring configuration file for a certain bean, its configured destruction method will be automatically invoked before the bean is destroyed.

// Example: Configuring destroy-method via annotation
@Component(destroyMethod = "cleanupResources")
public MyResourceBean { ... }