SpringIOC源码解析(3)


本来打算是SpringIOC源码分析写一篇文章,因为发布内容长度限制问题,最终是拆分为了三篇,需要查看一篇完整版的可以到CSDN地址: SpringIOC容器源码分析 查看。写SpringIOC源码分析文章主要是为了自己学习总结,期间也是参考了网上许多大神的分析文章,受益匪浅,希望之后能在此基础上继续总结精进。


finishBeanFactoryInitialization:初始化所有的 singleton beans

我们的重点当然是 finishBeanFactoryInitialization(beanFactory); 这个巨头了,这里会负责初始化所有的 singleton beans。

到目前为止,应该说 BeanFactory 已经创建完成,并且所有的实现了 BeanFactoryPostProcessor 接口的 Bean 都已经初始化并且其中的 postProcessBeanFactory(factory) 方法已经得到回调执行了。而且 Spring 已经“手动”注册了一些特殊的 Bean,如 environmentsystemProperties 等。

剩下的就是初始化 singleton beans 了,我们知道它们是单例的,如果没有设置懒加载,那么 Spring 会在接下来初始化所有的 singleton beans。

// AbstractApplicationContext.java 834

// 初始化剩余的 singleton beans
protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {

   // 首先,初始化此上下文的转换服务,即初始化名字为 conversionService 的 Bean  ******Spring中的conversionService
   // 什么,看代码这里没有初始化 Bean 啊!
   // 注意了,初始化的动作包装在 beanFactory.getBean(...) 中,这里先不说细节,先往下看吧
   if (beanFactory.containsBean(CONVERSION_SERVICE_BEAN_NAME) &&
         beanFactory.isTypeMatch(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class)) {
      beanFactory.setConversionService(
            beanFactory.getBean(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class));
   }

   // Register a default embedded value resolver if no bean post-processor
   // (such as a PropertyPlaceholderConfigurer bean) registered any before:
   // at this point, primarily for resolution in annotation attribute values.
   //如果beanFactory之前没有注册嵌入值解析器,则注册默认的嵌入值解析器:主要用于注解属性值的解析
   if (!beanFactory.hasEmbeddedValueResolver()) {
      beanFactory.addEmbeddedValueResolver(new StringValueResolver() {
         @Override
         public String resolveStringValue(String strVal) {
            return getEnvironment().resolvePlaceholders(strVal);
         }
      });
   }

   // 先初始化 LoadTimeWeaverAware 类型的 Bean.是 AspectJ 相关的内容
   String[] weaverAwareNames = beanFactory.getBeanNamesForType(LoadTimeWeaverAware.class, false, false);
   for (String weaverAwareName : weaverAwareNames) {
      getBean(weaverAwareName);
   }

   // Stop using the temporary ClassLoader for type matching.
   beanFactory.setTempClassLoader(null);

   //冻结所有bean定义,注册的bean定义不会被修改或进一步后处理,因为马上要创建 Bean 实例对象了
   beanFactory.freezeConfiguration();

   //开始初始化(实例化所有(非懒加载)单例对象)
   beanFactory.preInstantiateSingletons();
}

preInstantiateSingletons: 预初始化单例Bean

DefaultListableBeanFactory 728

@Override
public void preInstantiateSingletons() throws BeansException {
    if (this.logger.isDebugEnabled()) {
        this.logger.debug("Pre-instantiating singletons in " + this);
    }
 
    // Iterate over a copy to allow for init methods which in turn register new bean definitions.
    // While this may not be part of the regular factory bootstrap, it does otherwise work fine.
    // 1.创建beanDefinitionNames的副本beanNames用于后续的遍历,以允许init等方法注册新的bean定义
    List beanNames = new ArrayList(this.beanDefinitionNames);
 
    // Trigger initialization of all non-lazy singleton beans...
    // 2.遍历beanNames,触发所有非懒加载单例bean的初始化
    for (String beanName : beanNames) {
        // 3.获取beanName对应的MergedBeanDefinition
        RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);
        // 4.bd对应的Bean实例:不是抽象类 && 是单例 && 不是懒加载
        if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {
            // 5.判断beanName对应的bean是否为FactoryBean
            if (isFactoryBean(beanName)) {
                // 5.1 通过beanName获取FactoryBean实例
                // 通过getBean(&beanName)拿到的是FactoryBean本身;通过getBean(beanName)拿到的是FactoryBean创建的Bean实例
                final FactoryBean factory = (FactoryBean) getBean(FACTORY_BEAN_PREFIX + beanName);
                // 5.2 判断这个FactoryBean是否希望急切的初始化
                boolean isEagerInit;
                if (System.getSecurityManager() != null && factory instanceof SmartFactoryBean) {
                    isEagerInit = AccessController.doPrivileged(new PrivilegedAction() {
                        @Override
                        public Boolean run() {
                            return ((SmartFactoryBean) factory).isEagerInit();
                        }
                    }, getAccessControlContext());
                } else {
                    isEagerInit = (factory instanceof SmartFactoryBean &&
                            ((SmartFactoryBean) factory).isEagerInit());
                }
                if (isEagerInit) {
                    // 5.3 如果希望急切的初始化,则通过beanName获取bean实例
                    getBean(beanName);
                }
            } else {
                // 6.如果beanName对应的bean不是FactoryBean,只是普通Bean,通过beanName获取bean实例
                getBean(beanName);
            }
        }
    }
 
    // Trigger post-initialization callback for all applicable beans...
    // 7.遍历beanNames,触发所有SmartInitializingSingleton的后初始化回调
    for (String beanName : beanNames) {
        // 7.1 拿到beanName对应的bean实例
        Object singletonInstance = getSingleton(beanName);
        // 7.2 判断singletonInstance是否实现了SmartInitializingSingleton接口
        if (singletonInstance instanceof SmartInitializingSingleton) {
            final SmartInitializingSingleton smartSingleton = (SmartInitializingSingleton) singletonInstance;
            // 7.3 触发SmartInitializingSingleton实现类的afterSingletonsInstantiated方法
            if (System.getSecurityManager() != null) {
                AccessController.doPrivileged(new PrivilegedAction() {
                    @Override
                    public Object run() {
                        smartSingleton.afterSingletonsInstantiated();
                        return null;
                    }
                }, getAccessControlContext());
            } else {
                smartSingleton.afterSingletonsInstantiated();
            }
        }
    }
}
 
 

上面提到了FactoryBean,那么我们知道的BeanFactory与FactoryBean有什么关联,FactoryBean与普通Bean又有什么区别和联系. FactoryBean原理与使用

具体分析下上面的代码:

DefaultListableBeanFactory 875 --- AbstractBeanFactory 1282 如上标注代码块3

    protected RootBeanDefinition getMergedLocalBeanDefinition(String beanName) throws BeansException {
        // Quick check on the concurrent map first, with minimal locking.
        // 1.检查beanName对应的MergedBeanDefinition是否存在于缓存中
        RootBeanDefinition mbd = this.mergedBeanDefinitions.get(beanName);
        if (mbd != null) {
            // 2.如果存在于缓存中则直接返回
            return mbd;
        }
        // 3.如果不存在于缓存中
        // 3.1 getBeanDefinition(beanName): 获取beanName对应的BeanDefinition,从beanDefinitionMap缓存中获取
        // 3.2 getMergedBeanDefinition: 根据beanName和对应的BeanDefinition,获取MergedBeanDefinition
        return getMergedBeanDefinition(beanName, getBeanDefinition(beanName));
    }

AbstractBeanFactory 1315

方法注释:如果给定bean的定义是子bean定义,则通过与父bean合并,返回给定bean的RootBeanDefinition

protected RootBeanDefinition getMergedBeanDefinition(
        String beanName, BeanDefinition bd, BeanDefinition containingBd)
        throws BeanDefinitionStoreException {
    // 1.加锁再进行操作
    synchronized (this.mergedBeanDefinitions) {
        // 用于存储bd的MergedBeanDefinition,也就是该方法的结果
        RootBeanDefinition mbd = null;
 
        // Check with full lock now in order to enforce the same merged instance.
        if (containingBd == null) {
            // 2.检查beanName对应的MergedBeanDefinition是否存在于缓存中
            mbd = this.mergedBeanDefinitions.get(beanName);
        }
 
        // 3.如果beanName对应的MergedBeanDefinition不存在于缓存中
        if (mbd == null) {
            if (bd.getParentName() == null) {
                // 4.如果bd的parentName为空,代表bd没有父定义,无需与父定义进行合并操作,
                // 也就是bd的MergedBeanDefinition就是bd本身(可能需要转成RootBeanDefinition)
                // Use copy of given root bean definition.
                if (bd instanceof RootBeanDefinition) {
                    // 4.1 如果bd的类型为RootBeanDefinition,则bd的MergedBeanDefinition就是bd本身,则直接克隆一个副本
                    mbd = ((RootBeanDefinition) bd).cloneBeanDefinition();
                } else {
                    // 4.2 否则,将bd作为参数,构建一个RootBeanDefinition。
                    // 正常使用下,BeanDefinition在被加载后是GenericBeanDefinition或ScannedGenericBeanDefinition
                    mbd = new RootBeanDefinition(bd);
                }
            } else {
                // 5.否则,bd存在父定义,需要与父定义合并
                // Child bean definition: needs to be merged with parent.
                BeanDefinition pbd;
                try {
                    // 5.1 获取父定义的beanName
                    String parentBeanName = transformedBeanName(bd.getParentName());
                    // 5.2 如果父定义的beanName与该bean的beanName不同
                    if (!beanName.equals(parentBeanName)) {
                        // 5.3 获取父定义的MergedBeanDefinition(因为父定义也可能有父定义,也就是bd的爷爷定义...)
                        pbd = getMergedBeanDefinition(parentBeanName);
                    } else {
                        // 5.4 如果父定义的beanName与bd的beanName相同,则拿到父BeanFactory,
                        // 只有在存在父BeanFactory的情况下,才允许父定义beanName与自己相同,否则就是将自己设置为父定义
                        BeanFactory parent = getParentBeanFactory();
                        if (parent instanceof ConfigurableBeanFactory) {
                            // 5.5 如果父BeanFactory是ConfigurableBeanFactory,则通过父BeanFactory获取父定义的MergedBeanDefinition
                            pbd = ((ConfigurableBeanFactory) parent).getMergedBeanDefinition(parentBeanName);
                        } else {
                            // 5.6 如果父BeanFactory不是ConfigurableBeanFactory,则抛异常
                            throw new NoSuchBeanDefinitionException(parentBeanName,
                                    "Parent name '" + parentBeanName + "' is equal to bean name '" + beanName +
                                            "': cannot be resolved without an AbstractBeanFactory parent");
                        }
                    }
                } catch (NoSuchBeanDefinitionException ex) {
                    throw new BeanDefinitionStoreException(bd.getResourceDescription(), beanName,
                            "Could not resolve parent bean definition '" + bd.getParentName() + "'", ex);
                }
                // Deep copy with overridden values.
                // 5.7 使用父定义pbd构建一个新的RootBeanDefinition对象(深拷贝)
                mbd = new RootBeanDefinition(pbd);
                // 5.8 使用bd覆盖父定义
                mbd.overrideFrom(bd);
            }
 
            // Set default singleton scope, if not configured before.
            // 6.如果没有配置scope,则设置成默认的singleton
            if (!StringUtils.hasLength(mbd.getScope())) {
                mbd.setScope(RootBeanDefinition.SCOPE_SINGLETON);
            }
 
            // A bean contained in a non-singleton bean cannot be a singleton itself.
            // Let's correct this on the fly here, since this might be the result of
            // parent-child merging for the outer bean, in which case the original inner bean
            // definition will not have inherited the merged outer bean's singleton status.
            // 7.如果containingBd不为空 && containingBd不为singleton && mbd为singleton,则将mdb的scope设置为containingBd的scope
            if (containingBd != null && !containingBd.isSingleton() && mbd.isSingleton()) {
                mbd.setScope(containingBd.getScope());
            }
 
            // Cache the merged bean definition for the time being
            // (it might still get re-merged later on in order to pick up metadata changes)
            // 8.将beanName与mbd放到mergedBeanDefinitions缓存,以便之后可以直接使用
            if (containingBd == null && isCacheBeanMetadata()) {
                this.mergedBeanDefinitions.put(beanName, mbd);
            }
        }
 
        // 9.返回MergedBeanDefinition
        return mbd;
    }
}

AbstractBeanFactory 1079 如上标注代码块5

@Override
public boolean isFactoryBean(String name) throws NoSuchBeanDefinitionException {
    // 1.拿到真正的beanName(去掉&前缀、解析别名)
    String beanName = transformedBeanName(name);
 
    // 2.尝试从缓存获取Bean实例对象
    Object beanInstance = getSingleton(beanName, false);
    if (beanInstance != null) {
        // 3.beanInstance存在,则直接判断类型是否为FactoryBean
        return (beanInstance instanceof FactoryBean);
    } else if (containsSingleton(beanName)) {
        // 4.如果beanInstance为null,并且beanName在单例对象缓存中,则代表beanName对应的单例对象为空对象,返回false
        // null instance registered
        return false;
    }
 
    // No singleton instance found -> check bean definition.
    if (!containsBeanDefinition(beanName) && getParentBeanFactory() instanceof ConfigurableBeanFactory) {
        // 5.如果缓存中不存在此beanName && 父beanFactory是ConfigurableBeanFactory,则调用父BeanFactory判断是否为FactoryBean
        // No bean definition found in this factory -> delegate to parent.
        return ((ConfigurableBeanFactory) getParentBeanFactory()).isFactoryBean(name);
    }
    // 6.通过MergedBeanDefinition来检查beanName对应的Bean是否为FactoryBean
    return isFactoryBean(beanName, getMergedLocalBeanDefinition(beanName));
}

上面 isFactoryBean(String name)中代码块2:从缓存获取Bean实例对象
这段代码是Spring解决循环依赖的核心代码,关于循环依赖的分析单独一篇,此处不再赘述 spring中的循环引用

接下来,我们就进入到 getBean(beanName) 方法了,这个方法我们经常用来从 BeanFactory 中获取一个 Bean,而初始化的过程也封装到了这个方法里。

getBean

// AbstractBeanFactory 196

@Override
public Object getBean(String name) throws BeansException {
   return doGetBean(name, null, null, false);
}

// 我们在剖析初始化 Bean 的过程,但是 getBean 方法我们经常是用来从容器中获取 Bean 用的,注意切换思路,
// 已经初始化过了就从容器中直接返回,否则就先初始化再返回
@SuppressWarnings("unchecked")
protected  T doGetBean(
      final String name, final Class requiredType, final Object[] args, boolean typeCheckOnly)
      throws BeansException {
   // 获取一个 “正统的” beanName,处理两种情况,一个是前面说的 FactoryBean(前面带 ‘&’),
   // 一个是别名问题,因为这个方法是 getBean,获取 Bean 用的,你要是传一个别名进来,是完全可以的
   final String beanName = transformedBeanName(name);
  
   // 注意跟着这个,这个是返回值
   Object bean; 

   // 检查下是不是已经创建过了,已创建的单例Bean可以从缓存中直接获取
   Object sharedInstance = getSingleton(beanName);
  
   // 这里说下 args 呗,虽然看上去一点不重要。前面我们一路进来的时候都是 getBean(beanName),
   // 所以 args 传参其实是 null 的,但是如果 args 不为空的时候,那么意味着调用方不是希望获取 Bean,而是创建 Bean
   if (sharedInstance != null && args == null) {
      if (logger.isDebugEnabled()) {
         //如果beanName的实例存在于缓存中
         if (isSingletonCurrentlyInCreation(beanName)) {
            logger.debug("...");
         }
         else {
            logger.debug("Returning cached instance of singleton bean '" + beanName + "'");
         }
      }
      // 下面这个方法:如果是普通 Bean 的话,直接返回 sharedInstance,
      // 如果是 FactoryBean 的话,返回它创建的那个实例对象
      bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);
   }

   else {
      if (isPrototypeCurrentlyInCreation(beanName)) {
         // 创建过了此 beanName 的 prototype 类型的 bean,那么抛异常;  往往是因为陷入了循环引用
         // scope为prototype的循环依赖校验:如果beanName已经正在创建Bean实例中,而此时我们又要再一次创建beanName的实例,则代表出现了循环依赖,需要抛出异常。
         // 例子:如果存在A中有B的属性,B中有A的属性,那么当依赖注入的时候,就会产生当A还未创建完的时候因为对于B的创建再次返回创建A,造成循环依赖
         throw new BeanCurrentlyInCreationException(beanName);
      }

      // 获取parentBeanFactory
      BeanFactory parentBeanFactory = getParentBeanFactory();
      //如果父容器父容器存在 && beanName在当前BeanFactory中不存在Bean定义,则尝试从父容器中获取实例
      if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
         String nameToLookup = originalBeanName(name);
         if (args != null) {
            // 返回父容器的查询结果
            return (T) parentBeanFactory.getBean(nameToLookup, args);
         }
         else {
            // No args -> delegate to standard getBean method.
            return parentBeanFactory.getBean(nameToLookup, requiredType);
         }
      }

      if (!typeCheckOnly) {
         // 如果不是仅仅做类型检测,而是创建bean实例,这里要将beanName放到alreadyCreated缓存
         markBeanAsCreated(beanName);
      }

      /*
       * 稍稍总结一下:
       * 到这里的话,要准备创建 Bean 了,对于 singleton 的 Bean 来说,容器中还没创建过此 Bean;
       * 对于 prototype 的 Bean 来说,本来就是要创建一个新的 Bean。
       */
      try {
         final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
         checkMergedBeanDefinition(mbd, beanName, args);

         //拿到当前bean依赖的bean名称集合,在实例化自己之前,需要先实例化自己依赖的bean
         String[] dependsOn = mbd.getDependsOn();
         if (dependsOn != null) {
            for (String dep : dependsOn) {
               // 检查dep是否依赖于beanName,即检查是否存在循环依赖
               if (isDependent(beanName, dep)) {
                  throw new BeanCreationException(mbd.getResourceDescription(), beanName,
                        "Circular depends-on relationship between '" + beanName + "' and '" + dep + "'");
               }
               // 将dep和beanName的依赖关系注册到缓存中
               registerDependentBean(dep, beanName);
               // 获取dep对应的bean实例,如果dep还没有创建bean实例,则创建dep的bean实例
               getBean(dep);
            }
         }

         // 如果是 singleton scope 的,创建 singleton 的实例
         if (mbd.isSingleton()) {
             //scope为singleton的bean创建(新建了一个ObjectFactory,并且重写了getObject方法)
            sharedInstance = getSingleton(beanName, new ObjectFactory() {
               @Override
               public Object getObject() throws BeansException {
                  try {
                     // 执行创建 Bean,详情后面再说
                     return createBean(beanName, mbd, args);
                  }
                  catch (BeansException ex) {
                     destroySingleton(beanName);
                     throw ex;
                  }
               }
            });
            //返回beanName对应的实例对象
            bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
         }

         // 如果是 prototype scope 的,创建 prototype 的实例
         else if (mbd.isPrototype()) {
            // It's a prototype -> create a new instance.
            Object prototypeInstance = null;
            try {
               //创建实例前的操作(将beanName保存到prototypesCurrentlyInCreation缓存中)
               beforePrototypeCreation(beanName);
               // 执行创建 Bean
               prototypeInstance = createBean(beanName, mbd, args);
            }
            finally {
                //创建实例后的操作(将创建完的beanName从prototypesCurrentlyInCreation缓存中移除)
               afterPrototypeCreation(beanName);
            }
            //返回beanName对应的实例对象
            bean = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);
         }

         // 其他scope的bean创建,可能是request之类的
         // 根据scopeName,从缓存拿到scope实例
         else {
            String scopeName = mbd.getScope();
            final Scope scope = this.scopes.get(scopeName);
            if (scope == null) {
               throw new IllegalStateException("No Scope registered for scope name '" + scopeName + "'");
            }
            try {
                //其他scope的bean创建(新建了一个ObjectFactory,并且重写了getObject方法)
               Object scopedInstance = scope.get(beanName, new ObjectFactory() {
                  @Override
                  public Object getObject() throws BeansException {
                     //创建实例前的操作(将beanName保存到prototypesCurrentlyInCreation缓存中)
                     beforePrototypeCreation(beanName);
                     try {
                        //创建bean实例
                        return createBean(beanName, mbd, args);
                     }
                     finally {
                        //创建实例后的操作(将创建完的beanName从prototypesCurrentlyInCreation缓存中移除)
                        afterPrototypeCreation(beanName);
                     }
                  }
               });
               //返回beanName对应的实例对象
               bean = getObjectForBeanInstance(scopedInstance, name, beanName, mbd);
            }
            catch (IllegalStateException ex) {
               throw new BeanCreationException(beanName,
                     "Scope '" + scopeName + "' is not active for the current thread; consider " +
                     "defining a scoped proxy for this bean if you intend to refer to it from a singleton",
                     ex);
            }
         }
      }
      catch (BeansException ex) {
         // 如果创建bean实例过程中出现异常,则将beanName从alreadyCreated缓存中移除
         cleanupAfterBeanCreationFailure(beanName);
         throw ex;
      }
   }

   // 检查所需类型是否与实际的bean对象的类型匹配
   if (requiredType != null && bean != null && !requiredType.isInstance(bean)) {
      try {
         //类型不对,则尝试转换bean类型
         return getTypeConverter().convertIfNecessary(bean, requiredType);
      }
      catch (TypeMismatchException ex) {
         if (logger.isDebugEnabled()) {
            logger.debug("Failed to convert bean '" + name + "' to required type '" +
                  ClassUtils.getQualifiedName(requiredType) + "'", ex);
         }
         throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
      }
   }
   //返回创建出来的bean实例对象
   return (T) bean;
}
 
 

创建 Bean

接下来当然是分析 createBean 方法:创建Bean实例

protected abstract Object createBean(String beanName, RootBeanDefinition mbd, Object[] args) throws BeanCreationException;

第三个参数 args 数组代表创建实例需要的参数,不就是给构造方法用的参数,或者是工厂 Bean 的参数嘛,不过要注意,在我们的初始化阶段,args 是 null。

这回我们要到一个新的类了 AbstractAutowireCapableBeanFactory,看类名,AutowireCapable?类名是不是也说明了点问题了。

主要是为了以下场景,采用 @Autowired 注解注入属性值:

public class MessageServiceImpl implements MessageService {
    @Autowired
    private UserService userService;
  
    public String getMessage() {
        return userService.getMessage();
    }
}

// AbstractAutowireCapableBeanFactory 447

/**
 * Central method of this class: creates a bean instance,
 * populates the bean instance, applies post-processors, etc.
 * @see #doCreateBean
 */
@Override
protected Object createBean(String beanName, RootBeanDefinition mbd, Object[] args) throws BeanCreationException {
   if (logger.isDebugEnabled()) {
      logger.debug("Creating instance of bean '" + beanName + "'");
   }
   RootBeanDefinition mbdToUse = mbd;

   // 确保 BeanDefinition 中的 Class 被加载
   // Make sure bean class is actually resolved at this point, and
   // clone the bean definition in case of a dynamically resolved Class
   // which cannot be stored in the shared merged bean definition.     
   Class resolvedClass = resolveBeanClass(mbd, beanName);
   if (resolvedClass != null && !mbd.hasBeanClass() && mbd.getBeanClassName() != null) {
      mbdToUse = new RootBeanDefinition(mbd);
      mbdToUse.setBeanClass(resolvedClass);
   }

   // 准备方法覆写,这里又涉及到一个概念:MethodOverrides,它来自于 bean 定义中的 
   // 我在附录中也对这两个标签的相关知识点进行了介绍,读者可以移步去看看
   try {
      mbdToUse.prepareMethodOverrides();
   }
   catch (BeanDefinitionValidationException ex) {
      throw new BeanDefinitionStoreException(mbdToUse.getResourceDescription(),
            beanName, "Validation of method overrides failed", ex);
   }

   try {
      // 让 InstantiationAwareBeanPostProcessor 在这一步有机会返回代理,
      // 1.实例化前的处理,给InstantiationAwareBeanPostProcessor一个机会返回代理对象来替代真正的bean实例
      Object bean = resolveBeforeInstantiation(beanName, mbdToUse);
      //如果此时返回的代理对象部位null,则会跳过Spring默认的实例化过程,直接使用返回的bean
      if (bean != null) {
         return bean; 
      }
   }
   catch (Throwable ex) {
      throw new BeanCreationException(mbdToUse.getResourceDescription(), beanName,
            "BeanPostProcessor before instantiation of bean failed", ex);
   }
   // 创建Bean实例(真正创建Bean的方法)
   Object beanInstance = doCreateBean(beanName, mbdToUse, args);
   if (logger.isDebugEnabled()) {
      logger.debug("Finished creating instance of bean '" + beanName + "'");
   }
   return beanInstance;
}

分析下上面解析中的1:resolveBeforeInstantiation(beanName, mbdToUse)

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.
        ******************** 为什么这里一定不是合成Bean
        // 1.mbd不是合成的,并且BeanFactory中存在InstantiationAwareBeanPostProcessor
        if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
            // 2.解析beanName对应的Bean实例的类型
            Class targetType = determineTargetType(beanName, mbd);
            if (targetType != null) {
                // 3.实例化前的后置处理器应用(处理InstantiationAwareBeanPostProcessor)
                bean = applyBeanPostProcessorsBeforeInstantiation(targetType, beanName);
                if (bean != null) {
                    // 4.如果返回的bean不为空,会跳过Spring默认的实例化过程,
                    // 所以只能在这里调用BeanPostProcessor实现类的postProcessAfterInitialization方法
                    bean = applyBeanPostProcessorsAfterInitialization(bean, beanName);
                }
            }
        }
        // 5.如果bean不为空,则将beforeInstantiationResolved赋值为true,代表在实例化之前已经解析
        mbd.beforeInstantiationResolved = (bean != null);
    }
    return bean;
}

resolveBeforeInstantiation(beanName, mbdToUse) 3 --- applyBeanPostProcessorsBeforeInstantiation:
在此处应用InstantiationAwareBeanPostProcessor后置处理器,允许postProcessBeforeInstantiation方法返回bean对象的代理

protected Object applyBeanPostProcessorsBeforeInstantiation(Class beanClass, String beanName) {
    // 1.遍历当前BeanFactory中的BeanPostProcessor
    for (BeanPostProcessor bp : getBeanPostProcessors()) {
        // 2.应用InstantiationAwareBeanPostProcessor后置处理器,允许postProcessBeforeInstantiation方法返回bean对象的代理
        if (bp instanceof InstantiationAwareBeanPostProcessor) {
            InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
            // 3.执行postProcessBeforeInstantiation方法,在Bean实例化前操作,
            // 该方法可以返回一个构造完成的Bean实例,从而不会继续执行创建Bean实例的“正规的流程”,达到“短路”的效果。
            Object result = ibp.postProcessBeforeInstantiation(beanClass, beanName);
            if (result != null) {
                // 4.如果result不为空,也就是有后置处理器返回了bean实例对象,则会跳过Spring默认的实例化过程
                return result;
            }
        }
    }
    return null;
}

doCreateBean():正真执行创建Bean的过程

我们继续往里看 doCreateBean 这个方法:

/**
 * Actually create the specified bean. Pre-creation processing has already happened
 * at this point, e.g. checking {@code postProcessBeforeInstantiation} callbacks.
 * 

Differentiates between default bean instantiation, use of a * factory method, and autowiring a constructor. * @param beanName the name of the bean * @param mbd the merged bean definition for the bean * @param args explicit arguments to use for constructor or factory method invocation * @return a new instance of the bean * @throws BeanCreationException if the bean could not be created * @see #instantiateBean * @see #instantiateUsingFactoryMethod * @see #autowireConstructor */ protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final Object[] args) throws BeanCreationException { // Instantiate the bean. // 1.新建Bean包装类 BeanWrapper instanceWrapper = null; if (mbd.isSingleton()) { // 2.如果是FactoryBean,则需要先移除未完成的FactoryBean实例的缓存 instanceWrapper = this.factoryBeanInstanceCache.remove(beanName); } if (instanceWrapper == null) { // 3.根据beanName、mbd、args,使用对应的策略创建Bean实例,并返回包装类BeanWrapper instanceWrapper = createBeanInstance(beanName, mbd, args); } // 4.拿到创建好的Bean实例 final Object bean = (instanceWrapper != null ? instanceWrapper.getWrappedInstance() : null); // 5.拿到Bean实例的类型 Class beanType = (instanceWrapper != null ? instanceWrapper.getWrappedClass() : null); mbd.resolvedTargetType = beanType; // Allow post-processors to modify the merged bean definition. synchronized (mbd.postProcessingLock) { if (!mbd.postProcessed) { try { // 6.应用后置处理器MergedBeanDefinitionPostProcessor,允许修改MergedBeanDefinition, // Autowired注解正是通过此方法实现注入类型的预解析 applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName); } catch (Throwable ex) { throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Post-processing of merged bean definition failed", ex); } mbd.postProcessed = true; } } // Eagerly cache singletons to be able to resolve circular references // even when triggered by lifecycle interfaces like BeanFactoryAware. // 7.判断是否需要提早曝光实例:单例 && 允许循环依赖 && 当前bean正在创建中 boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences && isSingletonCurrentlyInCreation(beanName)); if (earlySingletonExposure) { if (logger.isTraceEnabled()) { logger.trace("Eagerly caching bean '" + beanName + "' to allow for resolving potential circular references"); } // 8.提前曝光beanName的ObjectFactory,用于解决循环引用 addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean)); } // Initialize the bean instance. 初始化bean实例。 Object exposedObject = bean; try { // 9.对bean进行属性填充;其中,可能存在依赖于其他bean的属性,则会递归初始化依赖的bean实例 populateBean(beanName, mbd, instanceWrapper); if (exposedObject != null) { // 10.对bean进行初始化 exposedObject = initializeBean(beanName, exposedObject, mbd); } } catch (Throwable ex) { if (ex instanceof BeanCreationException && beanName.equals(((BeanCreationException) ex).getBeanName())) { throw (BeanCreationException) ex; } else { throw new BeanCreationException( mbd.getResourceDescription(), beanName, "Initialization of bean failed", ex); } } if (earlySingletonExposure) { // 11.如果允许提前曝光实例,则进行循环依赖检查 Object earlySingletonReference = getSingleton(beanName, false); // 11.1 earlySingletonReference只有在当前解析的bean存在循环依赖的情况下才会不为空 if (earlySingletonReference != null) { if (exposedObject == bean) { // 11.2 如果exposedObject没有在initializeBean方法中被增强,则不影响之前的循环引用 exposedObject = earlySingletonReference; } else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) { // 11.3 如果exposedObject在initializeBean方法中被增强 && 不允许在循环引用的情况下使用注入原始bean实例 // && 当前bean有被其他bean依赖 // 11.4 拿到依赖当前bean的所有bean的beanName数组 String[] dependentBeans = getDependentBeans(beanName); Set actualDependentBeans = new LinkedHashSet(dependentBeans.length); for (String dependentBean : dependentBeans) { // 11.5 尝试移除这些bean的实例,因为这些bean依赖的bean已经被增强了,他们依赖的bean相当于脏数据 if (!removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) { // 11.6 移除失败的添加到 actualDependentBeans actualDependentBeans.add(dependentBean); } } if (!actualDependentBeans.isEmpty()) { // 11.7 如果存在移除失败的,则抛出异常,因为存在bean依赖了“脏数据” throw new BeanCurrentlyInCreationException(beanName, "Bean with name '" + beanName + "' has been injected into other beans [" + StringUtils.collectionToCommaDelimitedString(actualDependentBeans) + "] in its raw version as part of a circular reference, but has eventually been " + "wrapped. This means that said other beans do not use the final version of the " + "bean. This is often the result of over-eager type matching - consider using " + "'getBeanNamesOfType' with the 'allowEagerInit' flag turned off, for example."); } } } } // Register bean as disposable. try { // 12.注册用于销毁的bean,执行销毁操作的有三种:自定义destroy方法、DisposableBean接口、DestructionAwareBeanPostProcessor registerDisposableBeanIfNecessary(beanName, bean, mbd); } catch (BeanDefinitionValidationException ex) { throw new BeanCreationException( mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex); } // 13.完成创建并返回 return exposedObject; }

到这里,我们已经分析完了 doCreateBean 方法,总的来说,我们已经说完了整个初始化流程。

接下来我们挑 doCreateBean 中的三个细节出来说说,其实也就是Bean创建中最重要的三个步骤:

  • createBeanInstance方法:使用适当的实例化策略为指定的bean创建一个新实例:工厂方法、构造函数自动连接或简单实例化----bean实例创建
  • populateBean:用bean定义中的属性值填充给定BeanWrapper中的bean实例----属性填充
  • initializeBean:初始化给定的bean实例,应用工厂回调以及init方法和bean后处理器----回调应用
createBeanInstance: 创建Bean实例

// AbstractAutowireCapableBeanFactory 1161

protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, Object[] args) {
    // Make sure bean class is actually resolved at this point.
    // 解析bean的类型信息
    Class beanClass = resolveBeanClass(mbd, beanName);
 
    if (beanClass != null && !Modifier.isPublic(beanClass.getModifiers()) && !mbd.isNonPublicAccessAllowed()) {
        // beanClass不为空 && beanClass不是公开类(不是public修饰) && 该bean不允许访问非公共构造函数和方法,则抛异常
        throw new BeanCreationException(mbd.getResourceDescription(), beanName,
                "Bean class isn't public, and non-public access not allowed: " + beanClass.getName());
    }
 
    // 1.如果存在工厂方法则使用工厂方法实例化bean对象
    if (mbd.getFactoryMethodName() != null) {
        return instantiateUsingFactoryMethod(beanName, mbd, args);
    }
 
    // Shortcut when re-creating the same bean...
    // resolved: 构造函数或工厂方法是否已经解析过
    boolean resolved = false;
    // autowireNecessary: 是否需要自动注入(即是否需要解析构造函数参数)
    boolean autowireNecessary = false;
    if (args == null) {
        // 2.加锁  
        synchronized (mbd.constructorArgumentLock) {
            if (mbd.resolvedConstructorOrFactoryMethod != null) {
                // 2.1 如果resolvedConstructorOrFactoryMethod缓存不为空,则将resolved标记为已解析
                resolved = true;
                // 2.2 根据constructorArgumentsResolved判断是否需要自动注入
                autowireNecessary = mbd.constructorArgumentsResolved;
            }
        }
    }
 
    if (resolved) {
        // 3.如果已经解析过,则使用resolvedConstructorOrFactoryMethod缓存里解析好的构造函数方法
        if (autowireNecessary) {
            // 3.1 需要自动注入,则执行构造函数自动注入
            return autowireConstructor(beanName, mbd, null, null);
        } else {
            // 3.2 否则使用默认的构造函数进行bean的实例化
            return instantiateBean(beanName, mbd);
        }
    }
 
    // Need to determine the constructor...
    // 4.应用后置处理器SmartInstantiationAwareBeanPostProcessor,拿到bean的候选构造函数
    Constructor[] ctors = determineConstructorsFromBeanPostProcessors(beanClass, beanName);
    if (ctors != null ||
            mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_CONSTRUCTOR ||
            mbd.hasConstructorArgumentValues() || !ObjectUtils.isEmpty(args)) {
        // 5.如果ctors不为空 || mbd的注入方式为AUTOWIRE_CONSTRUCTOR || mdb定义了构造函数的参数值 || args不为空,则执行构造函数自动注入
        return autowireConstructor(beanName, mbd, ctors, args);
    }
 
    // No special handling: simply use no-arg constructor.
    // 6.没有特殊处理,则使用默认的无参构造函数进行bean的实例化
    return instantiateBean(beanName, mbd);
}
populateBean: bean 属性注入

// AbstractAutowireCapableBeanFactory 1203

protected void populateBean(String beanName, RootBeanDefinition mbd, BeanWrapper bw) {
   // bean 实例的所有属性都在这里了
   PropertyValues pvs = mbd.getPropertyValues();

   if (bw == null) {
      if (!pvs.isEmpty()) {
         throw new BeanCreationException(
               mbd.getResourceDescription(), beanName, "Cannot apply property values to null instance");
      }
      else {
         // Skip property population phase for null instance.
         return;
      }
   }

   // 到这步的时候,bean 实例化完成(通过工厂方法或构造方法),但是还没开始属性设值,
   // InstantiationAwareBeanPostProcessor 的实现类可以在这里对 bean 进行状态修改,
   // 我也没找到有实际的使用,所以我们暂且忽略这块吧
   boolean continueWithPropertyPopulation = true;
   if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
      for (BeanPostProcessor bp : getBeanPostProcessors()) {
         if (bp instanceof InstantiationAwareBeanPostProcessor) {
            InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
            // 如果返回 false,代表不需要进行后续的属性设值,也不需要再经过其他的 BeanPostProcessor 的处理
            if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {
               continueWithPropertyPopulation = false;
               break;
            }
         }
      }
   }

   if (!continueWithPropertyPopulation) {
      return;
   }

   if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_NAME ||
         mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_TYPE) {
      MutablePropertyValues newPvs = new MutablePropertyValues(pvs);

      // 通过名字找到所有属性值,如果是 bean 依赖,先初始化依赖的 bean。记录依赖关系
      if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_NAME) {
         autowireByName(beanName, mbd, bw, newPvs);
      }

      // 通过类型装配。复杂一些
      if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_TYPE) {
         autowireByType(beanName, mbd, bw, newPvs);
      }

      pvs = newPvs;
   }

   boolean hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors();
   boolean needsDepCheck = (mbd.getDependencyCheck() != RootBeanDefinition.DEPENDENCY_CHECK_NONE);

   if (hasInstAwareBpps || needsDepCheck) {
      PropertyDescriptor[] filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
      if (hasInstAwareBpps) {
         for (BeanPostProcessor bp : getBeanPostProcessors()) {
            if (bp instanceof InstantiationAwareBeanPostProcessor) {
               InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
               // 这里有个非常有用的 BeanPostProcessor 进到这里: AutowiredAnnotationBeanPostProcessor
               // 对采用 @Autowired、@Value 注解的依赖进行设值,这里的内容也是非常丰富的,不过本文不会展开说了,感兴趣的读者请自行研究
               pvs = ibp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName);
               if (pvs == null) {
                  return;
               }
            }
         }
      }
      if (needsDepCheck) {
         checkDependencies(beanName, mbd, filteredPds, pvs);
      }
   }
   // 设置 bean 实例的属性值
   applyPropertyValues(beanName, mbd, bw, pvs);
}
initializeBean:初始化Bean

// AbstractAutowireCapableBeanFactory 1773

protected Object initializeBean(final String beanName, final Object bean, RootBeanDefinition mbd) {
    // 1.激活Aware方法
    if (System.getSecurityManager() != null) {
        AccessController.doPrivileged(new PrivilegedAction() {
            @Override
            public Object run() {
                invokeAwareMethods(beanName, bean);
                return null;
            }
        }, getAccessControlContext());
    } else {
        invokeAwareMethods(beanName, bean);
    }
 
    Object wrappedBean = bean;
    if (mbd == null || !mbd.isSynthetic()) {
        // 2.在初始化前应用BeanPostProcessor的postProcessBeforeInitialization方法,允许对bean实例进行包装
        wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
    }
 
    try {
        // 3.调用初始化方法
        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()) {
        // 4.在初始化后应用BeanPostProcessor的postProcessAfterInitialization方法,允许对bean实例进行包装
        wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
    }
    // 5.返回wrappedBean
    return wrappedBean;
}
 
 

具体分析一下initializeBean中的几个方法:

invokeAwareMethods:aware方法调用
private void invokeAwareMethods(final String beanName, final Object bean) {
    if (bean instanceof Aware) {
        // BeanNameAware: 实现此接口的类想要拿到beanName,因此我们在这边赋值给它
        if (bean instanceof BeanNameAware) {
            ((BeanNameAware) bean).setBeanName(beanName);
        }
        // BeanClassLoaderAware:实现此接口的类想要拿到beanClassLoader,因此我们在这边赋值给它
        if (bean instanceof BeanClassLoaderAware) {
            ((BeanClassLoaderAware) bean).setBeanClassLoader(getBeanClassLoader());
        }
        // BeanFactoryAware: 实现此接口的类想要拿到 BeanFactory,因此我们在这边赋值给它
        if (bean instanceof BeanFactoryAware) {
            ((BeanFactoryAware) bean).setBeanFactory(AbstractAutowireCapableBeanFactory.this);
        }
    }
}

关于Spring中aware类的详细解析和使用分析进行单独说明 spring中的aware类原理解析与使用

applyBeanPostProcessorsBeforeInitialization:初始化前的后置处理器回调

注意几个重要的BeanPostProcessor实现,以及其在Bean的初始化过程中都起到了哪些作用,在这片文章中作了总结BeanPostProcessor和BeanFactoryPostProcessor族类原理及使用

@Override
public Object applyBeanPostProcessorsBeforeInitialization(Object existingBean, String beanName)
        throws BeansException {
 
    Object result = existingBean;
    // 1.遍历所有注册的BeanPostProcessor实现类,调用postProcessBeforeInitialization方法
    for (BeanPostProcessor beanProcessor : getBeanPostProcessors()) {
        // 2.在bean初始化方法执行前,调用postProcessBeforeInitialization方法
        result = beanProcessor.postProcessBeforeInitialization(result, beanName);
        if (result == null) {
            return result;
        }
    }
    return result;
}
invokeInitMethods:调用初始化方法
protected void invokeInitMethods(String beanName, final Object bean, RootBeanDefinition mbd)
        throws Throwable {
 
    // 1.首先检查bean是否实现了InitializingBean接口,如果是的话调用afterPropertiesSet方法
    boolean isInitializingBean = (bean instanceof InitializingBean);
    if (isInitializingBean && (mbd == null || !mbd.isExternallyManagedInitMethod("afterPropertiesSet"))) {
        if (logger.isDebugEnabled()) {
            logger.debug("Invoking afterPropertiesSet() on bean with name '" + beanName + "'");
        }
        // 2.调用afterPropertiesSet方法
        if (System.getSecurityManager() != null) {
            try {
                AccessController.doPrivileged(new PrivilegedExceptionAction() {
                    @Override
                    public Object run() throws Exception {
                        ((InitializingBean) bean).afterPropertiesSet();
                        return null;
                    }
                }, getAccessControlContext());
            } catch (PrivilegedActionException pae) {
                throw pae.getException();
            }
        } else {
            ((InitializingBean) bean).afterPropertiesSet();
        }
    }
 
    if (mbd != null) {
        String initMethodName = mbd.getInitMethodName();
        //3.方法名不为空 && 不是通过实现InitializingBean定义的方法名为afterPropertiesSet初始化方法 && 不是外部管理的初始化方法,调用自定义初始化方法
        if (initMethodName != null && !(isInitializingBean && "afterPropertiesSet".equals(initMethodName)) &&
                !mbd.isExternallyManagedInitMethod(initMethodName)) {
            invokeCustomInitMethod(beanName, bean, mbd);
        }
    }
}
 
 
invokeCustomInitMethod 调用自定义的初始化方法

自定义的初始化方法有两种实现:

  • Bean标签的init-method属性,对应于现在@Bean注解的initMethod属性,
  • @PostConstruct注解标记的方法
protected void invokeCustomInitMethod(String beanName, final Object bean, RootBeanDefinition mbd)
        throws Throwable {
    // 1.拿到初始化方法的方法名
    String initMethodName = mbd.getInitMethodName();
    // 2.根据方法名拿到方法
    final Method initMethod = (mbd.isNonPublicAccessAllowed() ?
            BeanUtils.findMethod(bean.getClass(), initMethodName) :
            ClassUtils.getMethodIfAvailable(bean.getClass(), initMethodName));
    if (initMethod == null) {
        // 3.如果不存在initMethodName对应的方法,并且是强制执行初始化方法(默认为强制), 则抛出异常
        if (mbd.isEnforceInitMethod()) {
            throw new BeanDefinitionValidationException("Couldn't find an init method named '" +
                    initMethodName + "' on bean with name '" + beanName + "'");
        } else {    // 如果设置了非强制,找不到则直接返回
            if (logger.isDebugEnabled()) {
                logger.debug("No default init method named '" + initMethodName +
                        "' found on bean with name '" + beanName + "'");
            }
            // Ignore non-existent default lifecycle methods.
            return;
        }
    }
 
    if (logger.isDebugEnabled()) {
        logger.debug("Invoking init method  '" + initMethodName + "' on bean with name '" + beanName + "'");
    }
 
    // 4.调用初始化方法
    if (System.getSecurityManager() != null) {
        AccessController.doPrivileged(new PrivilegedExceptionAction() {
            @Override
            public Object run() throws Exception {
                ReflectionUtils.makeAccessible(initMethod);
                return null;
            }
        });
        try {
            AccessController.doPrivileged(new PrivilegedExceptionAction() {
                @Override
                public Object run() throws Exception {
                    initMethod.invoke(bean);
                    return null;
                }
            }, getAccessControlContext());
        } catch (PrivilegedActionException pae) {
            InvocationTargetException ex = (InvocationTargetException) pae.getException();
            throw ex.getTargetException();
        }
    } else {
        try {
            ReflectionUtils.makeAccessible(initMethod);
            initMethod.invoke(bean);
        } catch (InvocationTargetException ex) {
            throw ex.getTargetException();
        }
    }
}
 
 
applyBeanPostProcessorsAfterInitialization:初始化后的后置处理器回调
@Override
public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName)
        throws BeansException {
 
    Object result = existingBean;
    // 1.遍历所有注册的BeanPostProcessor实现类,调用postProcessAfterInitialization方法
    for (BeanPostProcessor beanProcessor : getBeanPostProcessors()) {
        // 2.在bean初始化方法执行后,调用postProcessAfterInitialization方法
        result = beanProcessor.postProcessAfterInitialization(result, beanName);
        if (result == null) {
            return result;
        }
    }
    return result;
}

到此,Bean的创建过程完毕,下面回到doCreateBean方法中查看最后一块内容:Bean的销毁定义

registerDisposableBeanIfNecessary: 添加Bean销毁时的回调

同样的,类似于Bean的自定义初始化方法,实现自定义的Bean销毁方法也有两种方式:

  • Bean标签的destroy-method属性,对应于现在@Bean注解的destroyMethod属性,
  • @@PreDestroy注解标记的方法
    AbstractBeanFactory.java 1870
/**
* 将给定bean添加销毁bean列表中,通过实现DisposableBean接口或给定destroy方法,以在工厂关闭时调用(如果适用)。仅适用于单例
*/
protected void registerDisposableBeanIfNecessary(String beanName, Object bean, RootBeanDefinition mbd) {
    AccessControlContext acc = (System.getSecurityManager() != null ? getAccessControlContext() : null);
    // 1.mbd的scope不是prototype && 给定的bean需要在关闭时销毁
    if (!mbd.isPrototype() && requiresDestruction(bean, mbd)) {
        if (mbd.isSingleton()) {
            // 2.单例模式下注册用于销毁的bean到disposableBeans缓存,执行给定bean的所有销毁工作:
            // DestructionAwareBeanPostProcessors,DisposableBean接口,自定义销毁方法
            // 2.1 DisposableBeanAdapter:使用DisposableBeanAdapter来封装用于销毁的bean
            registerDisposableBean(beanName,
                    new DisposableBeanAdapter(bean, beanName, mbd, getBeanPostProcessors(), acc));
        } else {
            // 3.自定义scope处理
            // A bean with a custom scope...
            Scope scope = this.scopes.get(mbd.getScope());
            if (scope == null) {
                throw new IllegalStateException("No Scope registered for scope name '" + mbd.getScope() + "'");
            }
            scope.registerDestructionCallback(beanName,
                    new DisposableBeanAdapter(bean, beanName, mbd, getBeanPostProcessors(), acc));
        }
    }
}

至此,SpringIOC容器加载过程的源码分析结束,在之后的不断学习中会不断地查漏补缺,正确做到更加完善和更深的理解。

你可能感兴趣的:(SpringIOC源码解析(3))