在之前的文章中,我们比较过java bean和spring bean的区别,其中最主要的一点就是spring bean的生命周期是由容器管理的。这里我们就来了解下spring bean的生命周期。
生命周期
spring中的bean从beanDifinition阶段开始,主要经历下面几个过程:
- 实例化
- 属性填充
- BeanNameAware/BeanFactoryAware(这两个接口是为了让bean获取自己的beanName和所属的beanfactory)
- BeanPostProcessor的前置处理,通过postProcessBeforeInitialization()在bean的初始化前提供回调入口
- InitializingBean的afterPropertiesSet()方法
- 调用init-method 方法
- BeanPostProcessor的后置处理,通过postProcessAfterInitialization()在bean的初始化后提供回调入口
- * (以下流程只针对singleton的bean,prototype的bean交由调用方处理,不再由容器负责)
- DisposableBean的destroy()方法
- 调用destroy-method 方法
流程图
BeanPostProcessor理解
BeanPostProcessor作为bean的后置处理器,起到一个类似监听器的作用。
我们看下这个接口中的内容:
/**
* Apply this BeanPostProcessor to the given new bean instance <i>before</i> any bean
* initialization callbacks (like InitializingBean's {@code afterPropertiesSet}
* or a custom init-method). The bean will already be populated with property values.
* The returned bean instance may be a wrapper around the original.
* @param bean the new bean instance
* @param beanName the name of the bean
* @return the bean instance to use, either the original or a wrapped one;
* if {@code null}, no subsequent BeanPostProcessors will be invoked
* @throws org.springframework.beans.BeansException in case of errors
* @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet
*/
Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException;
/**
* Apply this BeanPostProcessor to the given new bean instance <i>after</i> any bean
* initialization callbacks (like InitializingBean's {@code afterPropertiesSet}
* or a custom init-method). The bean will already be populated with property values.
* The returned bean instance may be a wrapper around the original.
* <p>In case of a FactoryBean, this callback will be invoked for both the FactoryBean
* instance and the objects created by the FactoryBean (as of Spring 2.0). The
* post-processor can decide whether to apply to either the FactoryBean or created
* objects or both through corresponding {@code bean instanceof FactoryBean} checks.
* <p>This callback will also be invoked after a short-circuiting triggered by a
* {@link InstantiationAwareBeanPostProcessor#postProcessBeforeInstantiation} method,
* in contrast to all other BeanPostProcessor callbacks.
* @param bean the new bean instance
* @param beanName the name of the bean
* @return the bean instance to use, either the original or a wrapped one;
* if {@code null}, no subsequent BeanPostProcessors will be invoked
* @throws org.springframework.beans.BeansException in case of errors
* @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet
* @see org.springframework.beans.factory.FactoryBean
*/
Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException;
可以看到这个接口中只提供了两个方法:
postProcessbeforeInitialization:在bean实例化、依赖注入完成,bean初始化之前调用,是作为bean初始化前提供的回调入口;
postProcessAfterInitialization:在bean实例化、依赖注入完成。bean初始化之后调用,是作为bean初始化之后提供的回调入口。