Spring Bean生命周期详解和应用(中)
继上篇《Spring Bean生命周期详解和应用(上)》我们继续通过源码来深入下。
生命周期详解
Bean的完整生命周期经历各种方法调用,这些方法可以划分为以下几类:(结合上图,需要有如下顶层思维)
- Bean自身的方法:包括了Bean本身调用的方法和通过配置文件中
<bean>
的init-method和destroy-method指定的方法。 - Bean级生命周期接口方法:包括了BeanNameAware、BeanFactoryAware、ApplicationContextAware;当然也包括InitializingBean和DiposableBean接口的方法(可以被@PostConstruct和@PreDestory注解替代)
- 容器级生命周期接口方法:包括了InstantionAwareBeanProcessor和BeanPostProcessor。
- 工厂后处理器接口方法:包括了AspectJWwavingEnabler,ConfigurationClassPostProcessor,CustomAutowireConfigurer等非常有用的工厂后处理接口的方法,工厂后处理器也是容器级的。在应用上下文装配配置文件之后立即调用。
结合源码
入口当然是AbstractApplication#refresh,下面我们来看看整个过程,部分源码在时序图中已经贴出,详细源码可以调试查看。
- 执行AbstractApplication#invokeBeanFactoryPostProcessors:调用所有beanFactory的postProcessors。
- 执行PostProcessorRegisrtrationDelegate:执行所有注册BeanFactoryPostProcessors
String[] postProcessorNames =
beanFactory.getBeanNamesForType(BeanFactoryPostProcessor.class, true, false);
...
invokeBeanFactoryPostProcessors(nonOrderedPostProcessors, beanFactory);
...
for (BeanFactoryPostProcessor postProcessor : postProcessors) {
postProcessor.postProcessBeanFactory(beanFactory);
}
3. 执行MyBeanFactoryPostProcessor#postProcessBeanFactory:在Bean被实例化之前,允许被覆盖或添加属性。
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
log.info("调用BeanFactoryPostProcessor#postProcessBeanFactory");
BeanDefinition bd = beanFactory.getBeanDefinition("person");
bd.getPropertyValues().addPropertyValue("phone", "110");
}
4. 执行所有AbstractApplicationContext#finishBeanFactoryInitialization:实例化素有剩余的单例。 5. 执行AbstractAutowireCapableBeanFactory#createBean:
@Override
protected Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
throws BeanCreationException {
...
// Give BeanPostProcessors a chance to return a proxy instead of the target bean instance.
Object bean = resolveBeforeInstantiation(beanName, mbdToUse);
...
Object beanInstance = doCreateBean(beanName, mbdToUse, args);
...
}
6. 执行AbstractAutowireCapableBeanFactory#resolveBeforeInstantiation:
@Nullable
protected Object resolveBeforeInstantiation(String beanName, RootBeanDefinition mbd) {
Object bean = null;
// 可以看到BeanDefinition记录了生命周期的一些信息
if (!Boolean.FALSE.equals(mbd.beforeInstantiationResolved)) {
// Make sure bean class is actually resolved at this point.
if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
Class<?> targetType = determineTargetType(beanName, mbd);
if (targetType != null) {
bean = applyBeanPostProcessorsBeforeInstantiation(targetType, beanName);
// 可以发现postBeforeInstantuation可以抑制返回代理bean,有效抑制bean进行实例化,直接执行AfterIntialization。
if (bean != null) {
bean = applyBeanPostProcessorsAfterInitialization(bean, beanName);
}
}
}
mbd.beforeInstantiationResolved = (bean != null);
}
return bean;
}
7. 调用AbstractAutowireCapableBeanFactory#applyBeanPostProcessorsBeforeInstantiation:
@Nullable
protected Object applyBeanPostProcessorsBeforeInstantiation(Class beanClass, String beanName) {
for (BeanPostProcessor bp : getBeanPostProcessors()) {
if (bp instanceof InstantiationAwareBeanPostProcessor) {
InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
Object result = ibp.postProcessBeforeInstantiation(beanClass, beanName);
if (result != null) {
return result;
}
}
}
return null;
}
责任链的方式调用所有该bean的postProcessBeforeInstanttiation
- 调用MyInstantiationAwareBeanPostProcessor#postProcessBeforeInstantiation:
@Override
public Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) throws BeansException {
log.info("InstantiationAwareBeanPostProcessorAdapter调用postProcessBeforeInstantiation方法,beanClass:{},beanName:{}", beanClass.getName(), beanName);
return super.postProcessBeforeInstantiation(beanClass, beanName);
}
在实例化目标在bean之前执行,如果返回不为null那返回的就是代理bean,可以有效的抑制target bean的默认实例化。
- 执行AbstractAutowireCapableBeanFactory#doCreateBean:返回createBean方法继续执行doCreateBean。
- 执行AbstractAutowireCapableBeanFactory#createBeanInstance
- 执行AbstractAutowireCapableBeanFactory#insatntiateBean:使用无参构造器进行实例化。
- 执行Person构造器进行实例化。
- 执行AbstractAutowireCapableBeanFactory#populateBean:
protected void populateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw) {
...
// Give any InstantiationAwareBeanPostProcessors the opportunity to modify the
// state of the bean before properties are set. This can be used, for example,
// to support styles of field injection.
if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
for (BeanPostProcessor bp : getBeanPostProcessors()) {
if (bp instanceof InstantiationAwareBeanPostProcessor) {
InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
// 执行InstantiationAwareBeanPostProcessor#postProcessAfterInstantion
if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {
return;
}
}
}
}
...
if (hasInstAwareBpps) {
if (pvs == null) {
pvs = mbd.getPropertyValues();
}
for (BeanPostProcessor bp : getBeanPostProcessors()) {
if (bp instanceof InstantiationAwareBeanPostProcessor) {
InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
// 执行InsantiationAwareBeanPostProcess#postProcessProperties
PropertyValues pvsToUse = ibp.postProcessProperties(pvs, bw.getWrappedInstance(), beanName);
if (pvsToUse == null) {
if (filteredPds == null) {
filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
}
//填充属性值
pvsToUse = ibp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName);
if (pvsToUse == null) {
return;
}
}
pvs = pvsToUse;
}
}
}
if (needsDepCheck) {
if (filteredPds == null) {
filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
}
checkDependencies(beanName, mbd, filteredPds, pvs);
}
if (pvs != null) {
applyPropertyValues(beanName, mbd, bw, pvs);
}
}
14. 执行MyInstantiationAwareBeanPostProcessor#postProcessAfterInstantiation:
@Override
public boolean postProcessAfterInstantiation(Object bean, String beanName) throws BeansException {
log.info("InstantiationAwareBeanPostProcessorAdapter调用postProcessAfterInstantiation方法,bean:{},beanName:{}", bean, beanName);
return super.postProcessAfterInstantiation(bean, beanName);
}
在bean被实例化后,在Spring属性填充之前,执行自定义字段注入。如果返回true属性正常填充,返回false跳过属性填充还将阻止在bean实例在调用任何后续的InstantiationAwareBeanPostProcessor实例。
- 执行MyInstantiationAwareBeanPostProcessor#postProcessProperties:
@Override
public PropertyValues postProcessProperties(PropertyValues pvs, Object bean, String beanName) throws BeansException {
log.info("InstantiationAwareBeanPostProcessorAdapter调用postProcessProperties方法,pvs:{}", JSON.toJSONString(pvs.getPropertyValues()));
return super.postProcessProperties(pvs, bean, beanName);
}
在工厂将给定的属性应用于给定的bean之前对其进行后处理。
- 返回AbstractAutowireCapableBeanFactory#populateBean调用applyPropertyValues填充属性,执行Person的set方法。
- 继续AbstractAutowireCapableBeanFactory#doCreateBean往下执行AbstractAutowireCapableBeanFactory#initializeBean:
protected Object initializeBean(final String beanName, final Object bean, @Nullable RootBeanDefinition mbd) {
if (System.getSecurityManager() != null) {
AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
invokeAwareMethods(beanName, bean);
return null;
}, getAccessControlContext());
}
else {
//执行各种Aware如BeanFactoryAware、BeanNameAware
invokeAwareMethods(beanName, bean);
}
Object wrappedBean = bean;
if (mbd == null || !mbd.isSynthetic()) {
//执行BeanPostProcessor#postProcessBeforeInitialization、InstantiationAwareBeanPostProcessor#postProcessBeforeInitialization、@PostConstruct注释的方法
wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
}
try {
//执行IntializingBean#afterPropertiesSet、init-method指定的方法
invokeInitMethods(beanName, wrappedBean, mbd);
}
catch (Throwable ex) {
throw new BeanCreationException(
(mbd != null ? mbd.getResourceDescription() : null),
beanName, "Invocation of init method failed", ex);
}
if (mbd == null || !mbd.isSynthetic()) {
wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
}
return wrappedBean;
}
初始化给定的bean实例,应用工厂回调以及init方法和bean后处理器。 18. 执行AbstractAutowireCapableBeanFactory#invokeAwareMethods:
private void invokeAwareMethods(final String beanName, final Object bean) {
if (bean instanceof Aware) {
if (bean instanceof BeanNameAware) {
((BeanNameAware) bean).setBeanName(beanName);
}
if (bean instanceof BeanClassLoaderAware) {
ClassLoader bcl = getBeanClassLoader();
if (bcl != null) {
((BeanClassLoaderAware) bean).setBeanClassLoader(bcl);
}
}
if (bean instanceof BeanFactoryAware) {
((BeanFactoryAware) bean).setBeanFactory(AbstractAutowireCapableBeanFactory.this);
}
}
}
执行各种Aware
- 执行Person#setBeanName调用创建的bean设置在bean工厂中的bean name,Person#setBeanFactory将拥有的工厂提供给bean实例的回调。
- 执行AbstractAutowireCapableBeanFactory#applyBeanPostProcessorsBeforeIntialization:
@Override
public Object applyBeanPostProcessorsBeforeInitialization(Object existingBean, String beanName)
throws BeansException {
Object result = existingBean;
for (BeanPostProcessor processor : getBeanPostProcessors()) {
Object current = processor.postProcessBeforeInitialization(result, beanName);
if (current == null) {
return result;
}
result = current;
}
return result;
}
可以看到我们自定义的两个BeanPostProcessor。其中@PostContruct是属于CommonAnnotationBeanPostProcessor,但是顺序靠后因此后执行,但都属于BeanPostProcessor。
- 执行MyBeanFactoryPostProcessor/MyInsatantiationAwareBeanPostProcessor#postProcessorBeforeInitialization:在bean初始化之前,可能是个代理的bean
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
log.info("BeanPostProcessor接口调用postProcessBeforeInitialization");
return BeanPostProcessor.super.postProcessBeforeInitialization(bean, beanName);
}
22. 返回AbstractAutowireCapableBeanFactory#applyBeanPostProcessorsBeforeIntialization执行Person被注释的@PostConstruct:此时bean依赖注入已经完成,可以使用该注解注释方法进行任何初始化
-
返回AbstractAutowireCapableBeanFactory#initializeBean执行invokeInitMethods执行Person#afterPropertiesSet:此时bean依赖注入已经完成,可以使用该注解注释方法进行任何初始化。
-
返回AbstractAutowireCapableBeanFactory#invokeInitMethods执行Person#myInit、Person实现的InitializingBean#afterPropertiesSet方法。
-
返回AbstractAutowireCapableBeanFactory#applyBeanPostPostProcessorAfterInitialization执行MyBeanFactoryPostProcessor/MyInstantiationAwareBeanPostProcessor#PostProcessAfterInitialization:
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
log.info("BeanPostProcessor接口调用postProcessAfterInitialization");
return BeanPostProcessor.super.postProcessAfterInitialization(bean, beanName);
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
log.info("InstantiationAwareBeanPostProcessorAdapter调用postProcessAfterInitialization");
return super.postProcessAfterInitialization(bean, beanName);
}
在实例化后由BeanFactory或者BeanFactory创建的对象调用,自此会退出AbstractAutowireCapableBeanFactory#initializeBean方法。
- 执行AbstractApplicationContext#destroyBeans方法:
protected void destroyBeans() {
getBeanFactory().destroySingletons();
}
- 执行DisposableBeanAdapter#destroy:
public void destroy() {
if (!CollectionUtils.isEmpty(this.beanPostProcessors)) {
for (DestructionAwareBeanPostProcessor processor : this.beanPostProcessors) {
//执行@PreDestroy注释的方法
processor.postProcessBeforeDestruction(this.bean, this.beanName);
}
}
if (this.invokeDisposableBean) {
if (logger.isTraceEnabled()) {
logger.trace("Invoking destroy() on bean with name '" + this.beanName + "'");
}
try {
if (System.getSecurityManager() != null) {
AccessController.doPrivileged((PrivilegedExceptionAction) () -> {
((DisposableBean) this.bean).destroy();
return null;
}, this.acc);
}
else {
// 执行DisposableBean#destroy方法
((DisposableBean) this.bean).destroy();
}
}
catch (Throwable ex) {
String msg = "Invocation of destroy method failed on bean with name '" + this.beanName + "'";
if (logger.isDebugEnabled()) {
logger.warn(msg, ex);
}
else {
logger.warn(msg + ": " + ex);
}
}
}
if (this.destroyMethod != null) {
//执行Person destory-method方法
invokeCustomDestroyMethod(this.destroyMethod);
}
else if (this.destroyMethodName != null) {
Method methodToInvoke = determineDestroyMethod(this.destroyMethodName);
if (methodToInvoke != null) {
invokeCustomDestroyMethod(ClassUtils.getInterfaceMethodIfPossible(methodToInvoke));
}
}
}
贴出的代码注释了@PreDestory注释的方法、DisposableBean#destroy、destory-method指定的方法执行的位置。
总结
通过源码来“具象化”来了解生命周期是怎么实现的,AbstractApplicationContext作为容器的总入口来发起对单例的实例化,AbstractAutowireCapableFactory顾名思义用于负责bean的创建、填充属性、初始化以及中间的各种“勾子”是bean生命周期的核心。
通过源码也解惑了很多,比如执行顺序:@PostConstruct为啥比InitializingBean#afterPropetiesSet、init-method先执行,后续我们将继续了解下如何应用提供的这些“勾子”对生命周期进一步了解。
转载自:https://juejin.cn/post/7223790746615726140