Spring Bean Lifecycle
- Instantiate a bean.
- Configure the instantiated bean according to the Spring context.
- If this bean implements the
BeanNameAwareinterface, then call its implementedsetBeanName(String)method; the parameter passed is the ID value of the bean in the Spring configuration file. - If this bean implements the
BeanFactoryAwareinterface, then call its implementedsetBeanFactory(BeanFactory)method; the parameter passed is the Spring factory itself. - If this bean implements the
ApplicationContextAwareinterface, then call thesetApplicationContext(ApplicationContext)method; the parameter passed to it is the Spring context. - If a bean associates with the
BeanPostProcessorinterface, then call its implementedpostProcessBeforeInitialization(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. - 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() { ... }
If a certain bean associates with the
BeanPostProcessorinterface, then call thepostProcessAfterInitialization(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.When a bean is no longer needed, it will be cleaned up during the cleanup phase. If the bean implements the
DisposableBeaninterface, then Spring will call its implemented class'sdestroy()method before exiting.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 { ... }