重读系列之Spring源码解读--一个单例Bean的生命周期

903 阅读12分钟

在以前梳理SpringBean创建的源码的时候有说过,画一张其涉及的接口的流程图,现在补上这个坑。同时以前主要是重点关注Spring的代码逻辑(导致我自己现在去看也不是很能看下去)。在这个重读系列,我们从其的整体结构出发,如果不是特别的重要的逻辑,我们就不关注里面的一些细节逻辑。

一、DefaultListableBeanFactory

1、结构

​ SpringMVC的Bean容器的实现核心类就是这个DefaultListableBeanFactory,然后我们来看下其的层次结构

​ 其继承的类我们需要注意DefaultSingletonBeanRegistryAbstractBeanFactory,其中DefaultSingletonBeanRegistry类是单例Bean的存放,AbstractBeanFactory是获取Bean的整个逻辑处理。

​ 下面我们就直接来看获取Bean的过程,以下画的时序图并不是标准的时序图,只是为了说明概况整个流程,所以如果要画标准的时序图的话请学习资料。

二、第一阶段(拓展直接创建对象实例)

​ 在这里可以由InstantiationAwareBeanPostProcessor接口直接产生Bean,但Spring的注释是说,这个接口一般是供Spring框架内部使用的,不推荐直接使用这个接口。如果一定要拓展,其推荐使用InstantiationAwareBeanPostProcessorAdapter接口

public abstract class InstantiationAwareBeanPostProcessorAdapter implements SmartInstantiationAwareBeanPostProcessor {

​ 可以看到其实现了SmartInstantiationAwareBeanPostProcessor接口。

1、能拓展的接口

​ 这一阶段能拓展的接口``InstantiationAwareBeanPostProcessor,官方建议通过InstantiationAwareBeanPostProcessorAdapter`

2、流程图

​ 这就是获取Bean的第一阶段,可以看到其是通过InstantiationAwareBeanPostProcessor来产生Bean的,并且可以看到其调用的其他拓展接口就只有BeanPostProcessor接口了。

3、整体流程介绍

​ 1)、其的获取Bean的发起方法一般是getBean(String name),当然也可以Class作为入参getBean(Class<T> requiredType),不过其最终也还是会被转换为name的形式获取

@Override
public Object getBean(String name) throws BeansException {
   return doGetBean(name, null, null, false);
}
@Override
public <T> T getBean(Class<T> requiredType) throws BeansException {
   return getBean(requiredType, (Object[]) null);
}

​ 2)、我们可以看到其调用的是doGetBean方法

protected <T> T doGetBean(final String name, @Nullable final Class<T> requiredType,
      @Nullable final Object[] args, boolean typeCheckOnly)

​ 3)、然后可以看到如果是单例的话,其是调用getSingleton方法获取对应的Bean实例,但其又是通过createBean方法其创建的

if (mbd.isSingleton()) {
   sharedInstance = getSingleton(beanName, () -> {
      try {
         return createBean(beanName, mbd, args);
      }
      catch (BeansException ex) {
         // Explicitly remove instance from singleton cache: It might have been put there
         // eagerly by the creation process, to allow for circular reference resolution.
         // Also remove any beans that received a temporary reference to the bean.
         destroySingleton(beanName);
         throw ex;
      }
   });
   bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
}

​ 4)、然后通过mbdToUse.prepareMethodOverrides()再调用hasMethodOverrides()方法判断处理<lookup-method>标签。

@Override
protected Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
      throws BeanCreationException {
   RootBeanDefinition mbdToUse = mbd;

   Class<?> resolvedClass = resolveBeanClass(mbd, beanName);
      ..........
   // Prepare method overrides.
   try {
      mbdToUse.prepareMethodOverrides();
   }
   catch (BeanDefinitionValidationException ex) {
      throw new BeanDefinitionStoreException(mbdToUse.getResourceDescription(),
            beanName, "Validation of method overrides failed", ex);
   }

   try {
      // Give BeanPostProcessors a chance to return a proxy instead of the target bean instance.
      Object bean = resolveBeforeInstantiation(beanName, mbdToUse);
      if (bean != null) {
         return bean;
      }
   }
   catch (Throwable ex) {
      ........
   }

   try {
      Object beanInstance = doCreateBean(beanName, mbdToUse, args);
      return beanInstance;
   }
  .........
}
public void prepareMethodOverrides() throws BeanDefinitionValidationException {
   // Check that lookup methods exists.
   if (hasMethodOverrides()) {
      Set<MethodOverride> overrides = getMethodOverrides().getOverrides();
      synchronized (overrides) {
         for (MethodOverride mo : overrides) {
            prepareMethodOverride(mo);
         }
      }
   }
}
protected void prepareMethodOverride(MethodOverride mo) throws BeanDefinitionValidationException {
		int count = ClassUtils.getMethodCountForName(getBeanClass(), mo.getMethodName());
		.........
		else if (count == 1) {
			// Mark override as not overloaded, to avoid the overhead of arg type checking.
			mo.setOverloaded(false);
		}
	}

​ 5)、然后通过resolveBeforeInstantiation看能不能获取到Bean。

Object bean = resolveBeforeInstantiation(beanName, mbdToUse);

​ 6)、通过hasInstantiationAwareBeanPostProcessors()方法看有没有InstantiationAwareBeanPostProcessors接口的实现类,如果有,就调用该接口的postProcessBeforeInstantiation方法,如果这个接口有创建返回Bean,再调用BeanPostProcessor接口的postProcessAfterInitialization的方法,这样就完成了Bean的创建。

@Nullable
protected Object resolveBeforeInstantiation(String beanName, RootBeanDefinition mbd) {
   Object bean = null;
   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);
            if (bean != null) {
               bean = applyBeanPostProcessorsAfterInitialization(bean, beanName);
            }
         }
      }
      mbd.beforeInstantiationResolved = (bean != null);
   }
   return bean;
}
@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;
}
@Override
public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName)
      throws BeansException {

   Object result = existingBean;
   for (BeanPostProcessor beanProcessor : getBeanPostProcessors()) {
      Object current = beanProcessor.postProcessAfterInitialization(result, beanName);
      if (current == null) {
         return result;
      }
      result = current;
   }
   return result;
}

​ 我们看到如果是在这一阶段通过InstantiationAwareBeanPostProcessor接口产生了Bean返回的话,那其就只会调用BeanPostProcessor接口的postProcessAfterInitialization方法,不会再调用其的例如一些Aware等接口。

​ 如果在上面没有通过InstantiationAwareBeanPostProcessor产生Bean的话,就会接着往下调用doCreateBean(beanName, mbdToUse, args)方法。

三、第二阶段(拓展构造方法创建实例)

1、能拓展的接口

​ 这里能拓展的接口:

​ 1、BeanDefinition的Supplier

  2、BeanDefinition的<factory-method>工厂方法

​ 3、SmartInstantiationAwareBeanPostProcessor,这个也是建议使用适配器InstantiationAwareBeanPostProcessorAdapter去拓展

2、流程图

3、整体流程

protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final @Nullable Object[] args)
      throws BeanCreationException {
      .............
      instanceWrapper = createBeanInstance(beanName, mbd, args);
   }
   final Object bean = instanceWrapper.getWrappedInstance();
   Class<?> beanType = instanceWrapper.getWrappedClass();
       ............
   // Allow post-processors to modify the merged bean definition.
   synchronized (mbd.postProcessingLock) {
      if (!mbd.postProcessed) {
         try {
            applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
         }
         catch (Throwable ex) {
            throw new BeanCreationException(mbd.getResourceDescription(), beanName,
                  "Post-processing of merged bean definition failed", ex);
         }
         mbd.postProcessed = true;
      }
   }
      .............
   // Initialize the bean instance.
   Object exposedObject = bean;
   try {
      populateBean(beanName, mbd, instanceWrapper);
      exposedObject = initializeBean(beanName, exposedObject, mbd);
   }
   catch (Throwable ex) {
      ..........
   }
     ...........
   return exposedObject;
}

​ 1)、这里首先是通过 createBeanInstance(beanName, mbd, args)方法产生一个Bean实例的包装类,这个类里面已经有一个没有给属性赋值的Bean梳理了,例如其通过final Object bean = instanceWrapper.getWrappedInstance();获取这个梳理了。

​ 2)、现在我们来看下这个createBeanInstance方法

protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) {
   // Make sure bean class is actually resolved at this point.
   Class<?> beanClass = resolveBeanClass(mbd, beanName);
   .......
   Supplier<?> instanceSupplier = mbd.getInstanceSupplier();
   if (instanceSupplier != null) {
      return obtainFromSupplier(instanceSupplier, beanName);
   }

   if (mbd.getFactoryMethodName() != null)  {
      return instantiateUsingFactoryMethod(beanName, mbd, args);
   }
    ...........
   // Need to determine the constructor...
   Constructor<?>[] ctors = determineConstructorsFromBeanPostProcessors(beanClass, beanName);
   if (ctors != null ||
         mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_CONSTRUCTOR ||
         mbd.hasConstructorArgumentValues() || !ObjectUtils.isEmpty(args))  {
      return autowireConstructor(beanName, mbd, ctors, args);
   }
   // No special handling: simply use no-arg constructor.
   return instantiateBean(beanName, mbd);
}
@Nullable
public Supplier<?> getInstanceSupplier() {
   return this.instanceSupplier;
}
protected BeanWrapper obtainFromSupplier(Supplier<?> instanceSupplier, String beanName) {
   ......
   Object instance;
      instance = instanceSupplier.get();
    ......
   BeanWrapper bw = new BeanWrapperImpl(instance);
   initBeanWrapper(bw);
   return bw;
}

​ 可以看到这里其会最先通过Supplier来产生一个实例对象。

​ 3)、如果BeanDefinition没有对Supplier拓展设置。就会判断其有没有FactoryMethodName,通过工厂方法来创建实例。

if (mbd.getFactoryMethodName() != null)  {
   return instantiateUsingFactoryMethod(beanName, mbd, args);
}
protected BeanWrapper instantiateUsingFactoryMethod(
      String beanName, RootBeanDefinition mbd, @Nullable Object[] explicitArgs) {

   return new ConstructorResolver(this).instantiateUsingFactoryMethod(beanName, mbd, explicitArgs);
}
public BeanWrapper instantiateUsingFactoryMethod(
      final String beanName, final RootBeanDefinition mbd, @Nullable final Object[] explicitArgs) {

   BeanWrapperImpl bw = new BeanWrapperImpl();
   this.beanFactory.initBeanWrapper(bw);
       ............
   try {
      Object beanInstance;
         ......
      else {
         beanInstance = this.beanFactory.getInstantiationStrategy().instantiate(
               mbd, beanName, this.beanFactory, factoryBean, factoryMethodToUse, argsToUse);
      }
      bw.setBeanInstance(beanInstance);
      return bw;
   }
  .........
}
@Override
public Object instantiate(RootBeanDefinition bd, @Nullable String beanName, BeanFactory owner,
      @Nullable Object factoryBean, final Method factoryMethod, @Nullable Object... args) {
              .........
         Object result = factoryMethod.invoke(factoryBean, args);
         if (result == null) {
            result = new NullBean();
         }
         return result;
      }
       .......
}
<bean id="listInstance" class="org.springframework.beans.factory.xml.FactoryMethods"
     factory-method="listInstance"/>
private static List listInstance() {
   return Collections.EMPTY_LIST;
}

​ 上面这些就是通过FactoryMethod方法产生实例的过程。

​ 4)、如果其也没有拓展这个工厂方法,下面就会正式通过构造方法去产生这个Bean实例。不过这里就又会有一个拓展接口了。

​ 5)、我们先来看下determineConstructorsFromBeanPostProcessors(beanClass, beanName)方法

@Nullable
protected Constructor<?>[] determineConstructorsFromBeanPostProcessors(@Nullable Class<?> beanClass, String beanName)
      throws BeansException {

   if (beanClass != null && hasInstantiationAwareBeanPostProcessors()) {
      for (BeanPostProcessor bp : getBeanPostProcessors()) {
         if (bp instanceof SmartInstantiationAwareBeanPostProcessor) {
            SmartInstantiationAwareBeanPostProcessor ibp = (SmartInstantiationAwareBeanPostProcessor) bp;
            Constructor<?>[] ctors = ibp.determineCandidateConstructors(beanClass, beanName);
            if (ctors != null) {
               return ctors;
            }
         }
      }
   }
   return null;
}
@Override
public void addBeanPostProcessor(BeanPostProcessor beanPostProcessor) {
   Assert.notNull(beanPostProcessor, "BeanPostProcessor must not be null");
   this.beanPostProcessors.remove(beanPostProcessor);
   this.beanPostProcessors.add(beanPostProcessor);
   if (beanPostProcessor instanceof InstantiationAwareBeanPostProcessor) {
      this.hasInstantiationAwareBeanPostProcessors = true;
   }
   if (beanPostProcessor instanceof DestructionAwareBeanPostProcessor) {
      this.hasDestructionAwareBeanPostProcessors = true;
   }
}

​ 可以看到这里提供了SmartInstantiationAwareBeanPostProcessor接口来供你拓展去构建自定义的构造方法。调用其的determineCandidateConstructors方法。

@Nullable
default Constructor<?>[] determineCandidateConstructors(Class<?> beanClass, String beanName)
      throws BeansException {

   return null;
}

​ 6)、如果没有使用SmartInstantiationAwareBeanPostProcessor接口返回自定义的构造方法,就调用instantiateBean(beanName, mbd)方法来调用本身默认的构造方法。

protected BeanWrapper instantiateBean(final String beanName, final RootBeanDefinition mbd) {
   try {
      Object beanInstance;
      final BeanFactory parent = this;
      if (System.getSecurityManager() != null) {
         beanInstance = AccessController.doPrivileged((PrivilegedAction<Object>) () ->
               getInstantiationStrategy().instantiate(mbd, beanName, parent),
               getAccessControlContext());
      }
      else {
         beanInstance = getInstantiationStrategy().instantiate(mbd, beanName, parent);
      }
      BeanWrapper bw = new BeanWrapperImpl(beanInstance);
      initBeanWrapper(bw);
      return bw;
   }
   catch (Throwable ex) {
      throw new BeanCreationException(
            mbd.getResourceDescription(), beanName, "Instantiation of bean failed", ex);
   }
}
@Override
public Object instantiate(RootBeanDefinition bd, @Nullable String beanName, BeanFactory owner) {
   // Don't override the class with CGLIB if no overrides.
   if (!bd.hasMethodOverrides()) {
      .........
            final Class<?> clazz = bd.getBeanClass();
            if (clazz.isInterface()) {
               throw new BeanInstantiationException(clazz, "Specified class is an interface");
            }
            .......
                  constructorToUse = clazz.getDeclaredConstructor();
         .......
      return BeanUtils.instantiateClass(constructorToUse);
   }
   else {
      // Must generate CGLIB subclass.
      return instantiateWithMethodInjection(bd, beanName, owner);
   }
}

​ 可以看到这里如果是有方法重写,就会通过cglib去产生这个Bean梳理,也就是CglibSubclassingInstantiationStrategy类,目前我们是在SimpleInstantiationStrategy类中。

public class CglibSubclassingInstantiationStrategy extends SimpleInstantiationStrategy {

4、流程总结

​ 这一阶段主要有3个点来产生实例对象:

​ 1)、通过Supplier来产生实例(如果有自定义拓展的话)

​ 2)、可以通过<factory-method>这种工厂方法的形式来产生实例(如果有自定义拓展的话)

​ 3)、通过构造方法产生:其一是通过SmartInstantiationAwareBeanPostProcessor接口来返回自定义的构造方法、如果没有自定义,就通过默认的构造方法来产生Bean实例。

四、第三阶段(拓展实例的属性&实例修改)

1、流程图

2、整体流程

​ 到这里的时候已经通过前面的第二阶段创建了一个没有进行属性赋值的Bean实例对象了,这里现在就是去填充Bean的属性内容。

protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final @Nullable Object[] args)
      throws BeanCreationException {
    ..........
   final Object bean = instanceWrapper.getWrappedInstance();
   Class<?> beanType = instanceWrapper.getWrappedClass();
   .......
   // Allow post-processors to modify the merged bean definition.
   synchronized (mbd.postProcessingLock) {
      if (!mbd.postProcessed) {
         try {
            applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
         }
         catch (Throwable ex) {
            throw new BeanCreationException(mbd.getResourceDescription(), beanName,
                  "Post-processing of merged bean definition failed", ex);
         }
         mbd.postProcessed = true;
      }
   }
    .........
   // Initialize the bean instance.
   Object exposedObject = bean;
   try {
      populateBean(beanName, mbd, instanceWrapper);
      exposedObject = initializeBean(beanName, exposedObject, mbd);
   }
     ..........
        // Register bean as disposable.
	try {
		registerDisposableBeanIfNecessary(beanName, bean, mbd);
	}
    .......
   return exposedObject;
}

​ 1)、applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName)

protected void applyMergedBeanDefinitionPostProcessors(RootBeanDefinition mbd, Class<?> beanType, String beanName) {
   for (BeanPostProcessor bp : getBeanPostProcessors()) {
      if (bp instanceof MergedBeanDefinitionPostProcessor) {
         MergedBeanDefinitionPostProcessor bdp = (MergedBeanDefinitionPostProcessor) bp;
         bdp.postProcessMergedBeanDefinition(mbd, beanType, beanName);
      }
   }
}

​ 可以看到这里是去调用**MergedBeanDefinitionPostProcessor接口**的postProcessMergedBeanDefinition方法去拓展。这个方法的入参有RootBeanDefinition,所以你可以通过这个RootBeanDefinition去操作一些属性。

​ 2)、populateBean(beanName, mbd, instanceWrapper)

protected void populateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw) {
     .........
   if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
      for (BeanPostProcessor bp : getBeanPostProcessors()) {
         if (bp instanceof InstantiationAwareBeanPostProcessor) {
            InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
            if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {
               continueWithPropertyPopulation = false;
               break;
            }
         }
      }
   }
   if (!continueWithPropertyPopulation) {
      return;
   }
      ..........
   boolean hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors();
   boolean needsDepCheck = (mbd.getDependencyCheck() != RootBeanDefinition.DEPENDENCY_CHECK_NONE);
       ...........
      if (hasInstAwareBpps) {
         for (BeanPostProcessor bp : getBeanPostProcessors()) {
            if (bp instanceof InstantiationAwareBeanPostProcessor) {
               InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
               pvs = ibp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName);
               if (pvs == null) {
                  return;
               }
            }
         }
      }
     ........
    if (pvs != null) {
			// 设置 bw的属性
		applyPropertyValues(beanName, mbd, bw, pvs);
	}
}

​ 可以看到这里主要是通过InstantiationAwareBeanPostProcessor接口拓展。其的postProcessAfterInstantiation方法可以决定还要不要进行往下进行属性赋值。如果能,则会再调用其的postProcessPropertyValues方法,这个接口能操作其的PropertyValues

default boolean postProcessAfterInstantiation(Object bean, String beanName) throws BeansException {
   return true;
}
@Nullable
default PropertyValues postProcessPropertyValues(
      PropertyValues pvs, PropertyDescriptor[] pds, Object bean, String beanName) throws BeansException {
   return pvs;
}

​ 3)、initializeBean(beanName, exposedObject, mbd)

​ 这个方法是初始化Bean实例,主要是运行一些其他的拓展接口。到这里的时候已经进行了相应属性的赋值了

protected Object initializeBean(final String beanName, final Object bean, @Nullable RootBeanDefinition mbd) {
   .......
      invokeAwareMethods(beanName, bean);
   }
   Object wrappedBean = bean;
   if (mbd == null || !mbd.isSynthetic()) {
      wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
   }
   try {
      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;
}

​ 4、invokeAwareMethods(final String beanName, final Object bean)

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);
      }
   }
}

​ 可以看到这里是处理拓展的BeanNameAwareBeanClassLoaderAwareBeanFactoryAware接口。

​ 5)、applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName)

@Override
public Object applyBeanPostProcessorsBeforeInitialization(Object existingBean, String beanName)
      throws BeansException {

   Object result = existingBean;
   for (BeanPostProcessor beanProcessor : getBeanPostProcessors()) {
      Object current = beanProcessor.postProcessBeforeInitialization(result, beanName);
      if (current == null) {
         return result;
      }
      result = current;
   }
   return result;
}

​ 这里开始调用BeanPostProcessor接口的postProcessBeforeInitialization方法了。

@Nullable
default Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
   return bean;
}

​ 在这个接口你可以自己去处理这个Bean实例。

​ 6)、invokeInitMethods(beanName, wrappedBean, mbd)

protected void invokeInitMethods(String beanName, final Object bean, @Nullable RootBeanDefinition mbd)
      throws Throwable {

   boolean isInitializingBean = (bean instanceof InitializingBean);
   if (isInitializingBean && (mbd == null || !mbd.isExternallyManagedInitMethod("afterPropertiesSet"))) {
       ...........
      else {
         ((InitializingBean) bean).afterPropertiesSet();
      }
   }

   if (mbd != null && bean.getClass() != NullBean.class) {
      String initMethodName = mbd.getInitMethodName();
      if (StringUtils.hasLength(initMethodName) &&
            !(isInitializingBean && "afterPropertiesSet".equals(initMethodName)) &&
            !mbd.isExternallyManagedInitMethod(initMethodName)) {
         invokeCustomInitMethod(beanName, bean, mbd);
      }
   }
}
protected void invokeCustomInitMethod(String beanName, final Object bean, RootBeanDefinition mbd)
      throws Throwable {

   String initMethodName = mbd.getInitMethodName();
     ...........
   else {
      try {
         ReflectionUtils.makeAccessible(initMethod);
         initMethod.invoke(bean);
      ......
   }
}

​ 这里是运行initMethod,可以用InitializingBean接口去拓展,也可以使用<init-method>标签去处理(也等同于注解@PostConstruct)。要注意,init-method的名称不能是afterPropertiesSet,也就是不能与InitializingBean接口的方法同名,不然就不能运行自定义的init-method方法了。

​ 7)、applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName)

@Override
public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName)
      throws BeansException {

   Object result = existingBean;
   for (BeanPostProcessor beanProcessor : getBeanPostProcessors()) {
      Object current = beanProcessor.postProcessAfterInitialization(result, beanName);
      if (current == null) {
         return result;
      }
      result = current;
   }
   return result;
}

​ 可以看到在通过运行Aware接口 --> BeanPostProcessor接口的postProcessBeforeInitialization() --> InitializingBean接口 后,其会再去最后调用BeanPostProcessor接口的postProcessAfterInitialization()。

​ 8)、registerDisposableBeanIfNecessary(beanName, bean, mbd)

protected void registerDisposableBeanIfNecessary(String beanName, Object bean, RootBeanDefinition mbd) {
   AccessControlContext acc = (System.getSecurityManager() != null ? getAccessControlContext() : null);
   if (!mbd.isPrototype() && requiresDestruction(bean, mbd)) {
      if (mbd.isSingleton()) {
         // Register a DisposableBean implementation that performs all destruction
         // work for the given bean: DestructionAwareBeanPostProcessors,
         // DisposableBean interface, custom destroy method.
         registerDisposableBean(beanName,
               new DisposableBeanAdapter(bean, beanName, mbd, getBeanPostProcessors(), acc));
      }
public static boolean hasApplicableProcessors(Object bean, List<BeanPostProcessor> postProcessors) {
   if (!CollectionUtils.isEmpty(postProcessors)) {
      for (BeanPostProcessor processor : postProcessors) {
         if (processor instanceof DestructionAwareBeanPostProcessor) {
            DestructionAwareBeanPostProcessor dabpp = (DestructionAwareBeanPostProcessor) processor;
            if (dabpp.requiresDestruction(bean)) {
               return true;
            }
         }
      }
   }
   return false;
}
public class DefaultSingletonBeanRegistry extends SimpleAliasRegistry implements SingletonBeanRegistry {
    .......
   public void registerDisposableBean(String beanName, DisposableBean bean) {
     synchronized (this.disposableBeans) {
       this.disposableBeans.put(beanName, bean);
   }
}

​ 这里最后还可以DestructionAwareBeanPostProcessor接口来决定其需不需要将其添加到disposableBeans中。

至此,这个Bean实例的创建就完成了。

​ 下面我们就来看下Bean的销毁

五、第四阶段(销毁)

1、添加到disposableBeans阶段判断

​ 关于Bean的销毁,其是有用到上面的DestructionAwareBeanPostProcessor接口,不过其是用InitDestroyAnnotationBeanPostProcessor接口来管理的,我们在上面requiresDestruction(Object bean, RootBeanDefinition mbd) 有这个方法来判断其是否需要添加到disposableBeans中。

protected boolean requiresDestruction(Object bean, RootBeanDefinition mbd) {
   return (bean.getClass() != NullBean.class &&
         (DisposableBeanAdapter.hasDestroyMethod(bean, mbd) || (hasDestructionAwareBeanPostProcessors() &&
               DisposableBeanAdapter.hasApplicableProcessors(bean, getBeanPostProcessors()))));
}

​ 可以看到其有3个或条件:

​ 1)、其一就是判断是否实现的DisposableBean接口

public static boolean hasDestroyMethod(Object bean, RootBeanDefinition beanDefinition) {
   if (bean instanceof DisposableBean || bean instanceof AutoCloseable) {
      return true;
   }
   .....
}
public static boolean hasApplicableProcessors(Object bean, List<BeanPostProcessor> postProcessors) {
   if (!CollectionUtils.isEmpty(postProcessors)) {
      for (BeanPostProcessor processor : postProcessors) {
         if (processor instanceof DestructionAwareBeanPostProcessor) {
            DestructionAwareBeanPostProcessor dabpp = (DestructionAwareBeanPostProcessor) processor;
            if (dabpp.requiresDestruction(bean)) {
               return true;
            }
         }
      }
   }
   return false;
}
public class InitDestroyAnnotationBeanPostProcessor
		implements DestructionAwareBeanPostProcessor, MergedBeanDefinitionPostProcessor, PriorityOrdered, Serializable { 
    .........
	@Override
	public boolean requiresDestruction(Object bean) {
   	return findLifecycleMetadata(bean.getClass()).hasDestroyMethods();
	}

​ 2)、其二是通过InitDestroyAnnotationBeanPostProcessor类重写requiresDestruction方法。

public boolean hasDestroyMethods() {
   Collection<LifecycleElement> checkedDestroyMethods = this.checkedDestroyMethods;
   Collection<LifecycleElement> destroyMethodsToUse =
         (checkedDestroyMethods != null ? checkedDestroyMethods : this.destroyMethods);
   return !destroyMethodsToUse.isEmpty();
}
private class LifecycleMetadata {
    .......
   private final Collection<LifecycleElement> initMethods;
   private final Collection<LifecycleElement> destroyMethods;
    ...........
   public LifecycleMetadata(Class<?> targetClass, Collection<LifecycleElement> initMethods,
         Collection<LifecycleElement> destroyMethods) {

      this.targetClass = targetClass;
      this.initMethods = initMethods;
      this.destroyMethods = destroyMethods;
   }

​ 同时这个类还有initMethods

private LifecycleMetadata buildLifecycleMetadata(final Class<?> clazz) {
    ........
      ReflectionUtils.doWithLocalMethods(targetClass, method -> {
         if (initAnnotationType != null) {
            if (method.getAnnotation(initAnnotationType) != null) {
               LifecycleElement element = new LifecycleElement(method);
               currInitMethods.add(element);
              ..........
         }
         if (destroyAnnotationType != null) {
            if (method.getAnnotation(destroyAnnotationType) != null) {
             .......
         }
      });

      initMethods.addAll(0, currInitMethods);
      destroyMethods.addAll(currDestroyMethods);
      ........
   return new LifecycleMetadata(clazz, initMethods, destroyMethods);
}
public CommonAnnotationBeanPostProcessor() {
   setOrder(Ordered.LOWEST_PRECEDENCE - 3);
   setInitAnnotationType(PostConstruct.class);
   setDestroyAnnotationType(PreDestroy.class);
   ignoreResourceType("javax.xml.ws.WebServiceContext");
}
public void setInitAnnotationType(Class<? extends Annotation> initAnnotationType) {
   this.initAnnotationType = initAnnotationType;
}
public void setDestroyAnnotationType(Class<? extends Annotation> destroyAnnotationType) {
   this.destroyAnnotationType = destroyAnnotationType;
}

​ 这里就是destroy-method的判断。

2、销毁阶段

public void destroySingletons() {
   synchronized (this.singletonObjects) {
      this.singletonsCurrentlyInDestruction = true;
   }
   String[] disposableBeanNames;
   synchronized (this.disposableBeans) {
      disposableBeanNames = StringUtils.toStringArray(this.disposableBeans.keySet());
   }
   for (int i = disposableBeanNames.length - 1; i >= 0; i--) {
      destroySingleton(disposableBeanNames[i]);
   }

​ 可以看到这里就是遍历前面添加在disposableBeans中的Bean实例,然后通过destroySingleton方法去销毁。

public void destroySingleton(String beanName) {
   .......
   synchronized (this.disposableBeans) {
      disposableBean = (DisposableBean) this.disposableBeans.remove(beanName);
   }
   destroyBean(beanName, disposableBean);
}
protected void destroyBean(String beanName, @Nullable DisposableBean bean) {
      ...........
   // Actually destroy the bean now...
   if (bean != null) {
      try {
         bean.destroy();
      }
      ........
}

​ 在这里我们可以看到其会强转为DisposableBean,是因为如果单是destroy-method这种并没有实现接口是已经处理为了DisposableBeanAdapter,使用了适配器模式。

至此,整个单例Bean创建销毁过程会涉及到的一些接口就梳理完成。