Spring - IoC 源码阅读笔记:AbstractApplicationContext - finishBeanFactoryInitialization()

in Tech Java

前言

该方法会实例化所有剩余的非懒加载单例 bean。除了一些内部的 bean、BeanPostProcessor 接口实现的 bean 、 BeanFactoryPostProcessor 接口实现的 bean,所有剩余的非懒加载单例 bean 都会在这个方法中被实例化,并且触发 BeanPostProcessor 回调,同时是前面几个方法中最复杂也是最重要的,是整个 Spring IoC 核心中的核心。

finishBeanFactoryInitialization() 方法

    protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {
        // 为此上下文初始化转换服务
        // Initialize conversion service for this context.
        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.
        if (!beanFactory.hasEmbeddedValueResolver()) {
            // 注册默认的嵌入值解析器。主要用于注解属性值的解析
            beanFactory.addEmbeddedValueResolver(strVal -> getEnvironment().resolvePlaceholders(strVal));
        }

        // Initialize LoadTimeWeaverAware beans early to allow for registering their transformers early.
        // 初始化 LoadTimeWeaverAware Bean 实例对象。AOP 会用到
        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);

        // Allow for caching all bean definition metadata, not expecting further changes.
        // 允许缓存所有 bean 定义元数据。实例化前禁止修改
        beanFactory.freezeConfiguration();

        // Instantiate all remaining (non-lazy-init) singletons.
        // 实例化所有剩余的(非lazy init)单例。
        beanFactory.preInstantiateSingletons();
    }

preInstantiateSingletons() 方法

DefaultListableBeanFactory#preInstantiateSingletons

    public void preInstantiateSingletons() throws BeansException {
        if (logger.isTraceEnabled()) {
            logger.trace("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.
        // 在调用 obtainFreshBeanFactory() 或 invokeBeanFactoryPostProcessors() 方法时,
        // 已将 Bean 装载为 BeanDefinition,并存储在 beanDefinitionNames 中
        List<String> beanNames = new ArrayList<>(this.beanDefinitionNames);

        // Trigger initialization of all non-lazy singleton beans...
        for (String beanName : beanNames) {
            // 获取合并后的 BeanDefinition
            RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);
            // 不是抽象类 && 是单例 && 不是懒加载
            if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {
                // 判断 beanName 对应的 bean 是否为 FactoryBean
                if (isFactoryBean(beanName)) {
                    // 通过 getBean(&beanName) 拿到的是 FactoryBean 本身
                    // 通过 getBean(beanName) 拿到的是 FactoryBean 创建的 Bean 实例
                    Object bean = getBean(FACTORY_BEAN_PREFIX + beanName);
                    if (bean instanceof FactoryBean) {
                        final FactoryBean<?> factory = (FactoryBean<?>) bean;
                        // 立即实例化标识
                        boolean isEagerInit;
                        if (System.getSecurityManager() != null && factory instanceof SmartFactoryBean) {
                            isEagerInit = AccessController.doPrivileged((PrivilegedAction<Boolean>)
                                            ((SmartFactoryBean<?>) factory)::isEagerInit,
                                    getAccessControlContext());
                        }
                        else {
                            isEagerInit = (factory instanceof SmartFactoryBean &&
                                    ((SmartFactoryBean<?>) factory).isEagerInit());
                        }
                        // 需要实例化的话,在这里对 工厂Bean 进行初始化操作
                        if (isEagerInit) {
                            getBean(beanName);
                        }
                    }
                }
                else {
                    // 普通 Bean 实例化
                    getBean(beanName);
                }
            }
        }

        // Trigger post-initialization callback for all applicable beans...
        // 遍历 beanNames ,触发所有 SmartInitializingSingleton 的后初始化回调
        for (String beanName : beanNames) {
            // 获取 Bean 单例对象
            Object singletonInstance = getSingleton(beanName);
            if (singletonInstance instanceof SmartInitializingSingleton) {
                final SmartInitializingSingleton smartSingleton = (SmartInitializingSingleton) singletonInstance;
                if (System.getSecurityManager() != null) {
                    AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
                        smartSingleton.afterSingletonsInstantiated();
                        return null;
                    }, getAccessControlContext());
                }
                else {
                    smartSingleton.afterSingletonsInstantiated();
                }
            }
        }
    }

getMergedLocalBeanDefinition() 方法

    protected RootBeanDefinition getMergedLocalBeanDefinition(String beanName) throws BeansException {
        //先从缓存获取,拿不到再往下走
        // Quick check on the concurrent map first, with minimal locking.
        RootBeanDefinition mbd = this.mergedBeanDefinitions.get(beanName);
        if (mbd != null && !mbd.stale) {
            return mbd;
        }
        return getMergedBeanDefinition(beanName, getBeanDefinition(beanName));
    }

getMergedBeanDefinition() 方法

    protected RootBeanDefinition getMergedBeanDefinition(String beanName, BeanDefinition bd)
            throws BeanDefinitionStoreException {

        return getMergedBeanDefinition(beanName, bd, null);
    }

getMergedBeanDefinition() 方法

    protected RootBeanDefinition getMergedBeanDefinition(
            String beanName, BeanDefinition bd, @Nullable BeanDefinition containingBd)
            throws BeanDefinitionStoreException {

        // 加锁再处理
        synchronized (this.mergedBeanDefinitions) {
            RootBeanDefinition mbd = null;
            RootBeanDefinition previous = null;

            // Check with full lock now in order to enforce the same merged instance.
            if (containingBd == null) {
                // 从缓存中获取
                mbd = this.mergedBeanDefinitions.get(beanName);
            }

            if (mbd == null || mbd.stale) {
                previous = mbd;
                // parentName 为null,则表示没有 父定义
                if (bd.getParentName() == null) {
                    // Use copy of given root bean definition.
                    if (bd instanceof RootBeanDefinition) {
                        // 本身是 RootBeanDefinition ,直接克隆一个副本即可
                        mbd = ((RootBeanDefinition) bd).cloneBeanDefinition();
                    }
                    else {
                        // 否则,将bd作为参数,构建一个 RootBeanDefinition 。
                        // 正常使用下,BeanDefinition 在被加载后是GenericBeanDefinition 或 ScannedGenericBeanDefinition
                        mbd = new RootBeanDefinition(bd);
                    }
                }
                else {
                    // 存在父定义,需要与之合并
                    // Child bean definition: needs to be merged with parent.
                    BeanDefinition pbd;
                    try {
                        // 获取父定义的 beanName ,并转化名称。
                        // 主要是去掉 FactoryBean 里的 “&” 前缀,和解析别名
                        String parentBeanName = transformedBeanName(bd.getParentName());
                        // 当前 Bean 与父 Bean 名称不一样
                        if (!beanName.equals(parentBeanName)) {
                            // 这里可能存在 父定义也存在父定义,因此需要递归处理。
                            // 获取父定义的 MergedBeanDefinition
                            pbd = getMergedBeanDefinition(parentBeanName);
                        }
                        else {
                            // 只有存在父 BeanFactory 的情况下,才允许父定义 beanName 与自己相同
                            BeanFactory parent = getParentBeanFactory();
                            if (parent instanceof ConfigurableBeanFactory) {
                                // 通过父 BeanFactory ,获取父定义
                                pbd = ((ConfigurableBeanFactory) parent).getMergedBeanDefinition(parentBeanName);
                            }
                            else {
                                throw new NoSuchBeanDefinitionException(parentBeanName,
                                        "Parent name '" + parentBeanName + "' is equal to bean name '" + beanName +
                                        "': cannot be resolved without a ConfigurableBeanFactory parent");
                            }
                        }
                    }
                    catch (NoSuchBeanDefinitionException ex) {
                        throw new BeanDefinitionStoreException(bd.getResourceDescription(), beanName,
                                "Could not resolve parent bean definition '" + bd.getParentName() + "'", ex);
                    }
                    // Deep copy with overridden values.
                    // 使用父定义pbd构建一个新的 RootBeanDefinition 对象(深拷贝)
                    mbd = new RootBeanDefinition(pbd);
                    // 使用bd覆盖父定义
                    mbd.overrideFrom(bd);
                }

                // Set default singleton scope, if not configured before.
                // 如果没有配置作用域的话,则使用默认 单例
                if (!StringUtils.hasLength(mbd.getScope())) {
                    mbd.setScope(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.
                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)
                if (containingBd == null && isCacheBeanMetadata()) {
                    // 添加进缓存
                    this.mergedBeanDefinitions.put(beanName, mbd);
                }
            }
            if (previous != null) {
                copyRelevantMergedBeanDefinitionCaches(previous, mbd);
            }
            return mbd;
        }
    }

getBean() 方法

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

doGetBean() 方法

    @SuppressWarnings("unchecked")
    protected <T> T doGetBean(final String name, @Nullable final Class<T> requiredType,
            @Nullable final Object[] args, boolean typeCheckOnly) throws BeansException {
        // 去除 FactoryBean 前缀“$”
        final String beanName = transformedBeanName(name);
        Object bean;

        // Eagerly check singleton cache for manually registered singletons.
        // 优先从单例缓存中获取 beanName 对应的实例
        Object sharedInstance = getSingleton(beanName);
        if (sharedInstance != null && args == null) {
            if (logger.isTraceEnabled()) {
                if (isSingletonCurrentlyInCreation(beanName)) {
                    logger.trace("Returning eagerly cached instance of singleton bean '" + beanName +
                            "' that is not fully initialized yet - a consequence of a circular reference");
                }
                else {
                    logger.trace("Returning cached instance of singleton bean '" + beanName + "'");
                }
            }
            // 主要用于 FactoryBean 的特殊处理,普通 Bean会 直接返回 sharedInstance 本身
            bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);
        }

        else {
            // Fail if we're already creating this bean instance:
            // We're assumably within a circular reference.
            // scope为prototype的循环依赖校验:如果 beanName 已经正在创建 Bean 实例中,而此时我们又要再一次创建 beanName 的实例,则代表出现了循环依赖,需要抛出异常。
            // 例子:如果存在A中有B的属性,B中有A的属性,那么当依赖注入的时候,就会产生当A还未创建完的时候因为对于B的创建再次返回创建A,造成循环依赖
            if (isPrototypeCurrentlyInCreation(beanName)) {
                throw new BeanCurrentlyInCreationException(beanName);
            }

            // Check if bean definition exists in this factory.
            // 检查 bean 定义是否存在于 factory
            BeanFactory parentBeanFactory = getParentBeanFactory();
            if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
                // Not found -> check parent.
                // bean 定义不存在于当前 BeanFactory 中,尝试从 parentBeanFactory 获取
                String nameToLookup = originalBeanName(name);
                if (parentBeanFactory instanceof AbstractBeanFactory) {
                    return ((AbstractBeanFactory) parentBeanFactory).doGetBean(
                            nameToLookup, requiredType, args, typeCheckOnly);
                }
                else if (args != null) {
                    // Delegation to parent with explicit args.
                    return (T) parentBeanFactory.getBean(nameToLookup, args);
                }
                else if (requiredType != null) {
                    // No args -> delegate to standard getBean method.
                    return parentBeanFactory.getBean(nameToLookup, requiredType);
                }
                else {
                    return (T) parentBeanFactory.getBean(nameToLookup);
                }
            }

            if (!typeCheckOnly) {
                // 将 beanName 放到 alreadyCreated 缓存
                markBeanAsCreated(beanName);
            }

            try {
                // 重新获取 MergedBeanDefinition。markBeanAsCreated 中可能会清除 MergedBeanDefinition
                final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
                checkMergedBeanDefinition(mbd, beanName, args);

                // Guarantee initialization of beans that the current bean depends on.
                // 优先处理 bean 的依赖
                // SpringBoot 可使用注解 @DependsOn 来加载依赖
                String[] dependsOn = mbd.getDependsOn();
                if (dependsOn != null) {
                    for (String dep : dependsOn) {
                        // 是否存在循环依赖
                        if (isDependent(beanName, dep)) {
                            throw new BeanCreationException(mbd.getResourceDescription(), beanName,
                                    "Circular depends-on relationship between '" + beanName + "' and '" + dep + "'");
                        }
                        // 将依赖关系注册到 LinkedHashSet 缓存中
                        registerDependentBean(dep, beanName);
                        try {
                            // 获取 dep 对应的 bean 实例,如果 dep 还没有创建 bean 实例,则创建 dep 的 bean 实例
                            getBean(dep);
                        }
                        catch (NoSuchBeanDefinitionException ex) {
                            throw new BeanCreationException(mbd.getResourceDescription(), beanName,
                                    "'" + beanName + "' depends on missing bean '" + dep + "'", ex);
                        }
                    }
                }

                // Create bean instance.
                // 按不同的 scope 进行 bean 的创建
                if (mbd.isSingleton()) {
                    // 新建了一个 ObjectFactory ,并且重写了 getObject 方法
                    // ObjectFactory 使用了@FunctionalInterface 注解
                    // 会在执行 getSingleton 过程中调用 getObject 方法,回调到下面的 createBean 方法
                    sharedInstance = getSingleton(beanName, () -> {
                        try {
                            // 创建Bean实例
                            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;
                        }
                    });
                    // 获取 beanName 对应的实例对象
                    bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
                }

                else if (mbd.isPrototype()) {
                    // It's a prototype -> create a new instance.
                    Object prototypeInstance = null;
                    try {
                        // 将 beanName 保存到 prototypesCurrentlyInCreation 缓存中
                        beforePrototypeCreation(beanName);
                        prototypeInstance = createBean(beanName, mbd, args);
                    }
                    finally {
                        // 将创建完的 beanName 从 prototypesCurrentlyInCreation 缓存中移除
                        afterPrototypeCreation(beanName);
                    }
                    // 获取 beanName 对应的实例对象
                    bean = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);
                }

                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 {
                        Object scopedInstance = scope.get(beanName, () -> {
                            beforePrototypeCreation(beanName);
                            try {
                                return createBean(beanName, mbd, args);
                            }
                            finally {
                                afterPrototypeCreation(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) {
                cleanupAfterBeanCreationFailure(beanName);
                throw ex;
            }
        }

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

getObjectForBeanInstance() 方法

    protected Object getObjectForBeanInstance(
            Object beanInstance, String name, String beanName, @Nullable RootBeanDefinition mbd) {

        // Don't let calling code try to dereference the factory if the bean isn't a factory.
        // beanName 是否以 “&” 开头
        if (BeanFactoryUtils.isFactoryDereference(name)) {
            if (beanInstance instanceof NullBean) {
                return beanInstance;
            }
            // 不是 FactoryBean,直接抛异常
            if (!(beanInstance instanceof FactoryBean)) {
                throw new BeanIsNotAFactoryException(beanName, beanInstance.getClass());
            }
            if (mbd != null) {
                mbd.isFactoryBean = true;
            }
            return beanInstance;
        }

        // Now we have the bean instance, which may be a normal bean or a FactoryBean.
        // If it's a FactoryBean, we use it to create a bean instance, unless the
        // caller actually wants a reference to the factory.
        // 非 FactoryBean ,直接返回
        if (!(beanInstance instanceof FactoryBean)) {
            return beanInstance;
        }

        Object object = null;
        if (mbd != null) {
            mbd.isFactoryBean = true;
        }
        else {
            // 从 factoryBeanObjectCache 缓存中获取该 FactoryBean 创建的对象实例
            object = getCachedObjectForFactoryBean(beanName);
        }
        if (object == null) {
            // Return bean instance from factory.
            // 只有beanInstance是FactoryBean才能走到这边,因此直接强转
            FactoryBean<?> factory = (FactoryBean<?>) beanInstance;
            // Caches object obtained from FactoryBean if it is a singleton.
            if (mbd == null && containsBeanDefinition(beanName)) {
                mbd = getMergedLocalBeanDefinition(beanName);
            }
            // mbd是否是合成后的
            boolean synthetic = (mbd != null && mbd.isSynthetic());
            // 从 FactoryBean 获取对象实例
            object = getObjectFromFactoryBean(factory, beanName, !synthetic);
        }
        return object;
    }

getObjectFromFactoryBean() 方法


    protected Object getObjectFromFactoryBean(FactoryBean<?> factory, String beanName, boolean shouldPostProcess) {
        if (factory.isSingleton() && containsSingleton(beanName)) {
            synchronized (getSingletonMutex()) {
                // 从 FactoryBean 创建的单例对象的缓存中获取该 bean 实例
                Object object = this.factoryBeanObjectCache.get(beanName);
                if (object == null) {
                    // 调用 FactoryBean 的 getObject 方法获取对象实例
                    object = doGetObjectFromFactoryBean(factory, beanName);
                    // Only post-process and store if not put there already during getObject() call above
                    // (e.g. because of circular reference processing triggered by custom getBean calls)
                    // 如果该beanName已经在缓存中存在,则将object替换成缓存中的
                    Object alreadyThere = this.factoryBeanObjectCache.get(beanName);
                    if (alreadyThere != null) {
                        object = alreadyThere;
                    }
                    else {
                        if (shouldPostProcess) {
                            if (isSingletonCurrentlyInCreation(beanName)) {
                                // Temporarily return non-post-processed object, not storing it yet..
                                // 没有后处理,直接返回
                                return object;
                            }
                            // 缓存 beanName ,避免冲突
                            beforeSingletonCreation(beanName);
                            try {
                                // 执行 BeanPostProcessor 的 postProcessBeforeInitialization() 方法
                                object = postProcessObjectFromFactoryBean(object, beanName);
                            }
                            catch (Throwable ex) {
                                throw new BeanCreationException(beanName,
                                        "Post-processing of FactoryBean's singleton object failed", ex);
                            }
                            finally {
                                // 删除缓存的 beanName
                                afterSingletonCreation(beanName);
                            }
                        }
                        if (containsSingleton(beanName)) {
                            // 如果是单例对象,则缓存到 factoryBeanObjectCache
                            this.factoryBeanObjectCache.put(beanName, object);
                        }
                    }
                }
                return object;
            }
        }
        else {
            // 调用 FactoryBean 的 getObject 方法获取对象实例
            Object object = doGetObjectFromFactoryBean(factory, beanName);
            if (shouldPostProcess) {
                try {
                    object = postProcessObjectFromFactoryBean(object, beanName);
                }
                catch (Throwable ex) {
                    throw new BeanCreationException(beanName, "Post-processing of FactoryBean's object failed", ex);
                }
            }
            return object;
        }
    }

doGetObjectFromFactoryBean() 方法

    private Object doGetObjectFromFactoryBean(final FactoryBean<?> factory, final String beanName)
            throws BeanCreationException {

        Object object;
        try {
            if (System.getSecurityManager() != null) {
                AccessControlContext acc = getAccessControlContext();
                try {
                    // 带权限验证的
                    object = AccessController.doPrivileged((PrivilegedExceptionAction<Object>) factory::getObject, acc);
                }
                catch (PrivilegedActionException pae) {
                    throw pae.getException();
                }
            }
            else {
                // 不带权限验证的
                object = factory.getObject();
            }
        }
        catch (FactoryBeanNotInitializedException ex) {
            throw new BeanCurrentlyInCreationException(beanName, ex.toString());
        }
        catch (Throwable ex) {
            throw new BeanCreationException(beanName, "FactoryBean threw exception on object creation", ex);
        }

        // Do not accept a null value for a FactoryBean that's not fully
        // initialized yet: Many FactoryBeans just return null then.
        // 不接受一个尚未完全初始化的 FactoryBean 的 getObject 返回的空值
        if (object == null) {
            if (isSingletonCurrentlyInCreation(beanName)) {
                throw new BeanCurrentlyInCreationException(
                        beanName, "FactoryBean which is currently in creation returned null from getObject");
            }
            object = new NullBean();
        }
        return object;
    }

postProcessObjectFromFactoryBean() 方法

    @Override
    protected Object postProcessObjectFromFactoryBean(Object object, String beanName) {
        return applyBeanPostProcessorsAfterInitialization(object, beanName);
    }

applyBeanPostProcessorsAfterInitialization() 方法

    // 遍历所有注册的 BeanPostProcessor 实现类,调用 postProcessAfterInitialization 方法
    @Override
    public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName)
            throws BeansException {

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

isDependent() 方法

    protected boolean isDependent(String beanName, String dependentBeanName) {
        synchronized (this.dependentBeanMap) {
            return isDependent(beanName, dependentBeanName, null);
        }
    }

    private boolean isDependent(String beanName, String dependentBeanName, @Nullable Set<String> alreadySeen) {
        if (alreadySeen != null && alreadySeen.contains(beanName)) {
            // 已经检查过了 
            return false;
        }
        // 将别名解析为真正的名称
        String canonicalName = canonicalName(beanName);
        // 获取依赖 canonicalName 的名称集合
        Set<String> dependentBeans = this.dependentBeanMap.get(canonicalName);
        // 不存在依赖
        if (dependentBeans == null) {
            return false;
        }
        // 存在依赖
        if (dependentBeans.contains(dependentBeanName)) {
            return true;
        }
        // 循环检查,即检查依赖 canonicalName 的所有 beanName 是否存在被 dependentBeanName 依赖的(即隔层依赖)
        for (String transitiveDependency : dependentBeans) {
            if (alreadySeen == null) {
                alreadySeen = new HashSet<>();
            }
            alreadySeen.add(beanName);
            if (isDependent(transitiveDependency, dependentBeanName, alreadySeen)) {
                return true;
            }
        }
        return false;
    }

getSingleton() 方法

    @Override
    @Nullable
    public Object getSingleton(String beanName) {
        return getSingleton(beanName, true);
    }
    // Spring 解决循环引用的核心代码
    @Nullable
    protected Object getSingleton(String beanName, boolean allowEarlyReference) {
        // 尝试从单例缓存获取单例对象
        Object singletonObject = this.singletonObjects.get(beanName);
        if (singletonObject == null && isSingletonCurrentlyInCreation(beanName)) {
            // 加锁避免重复创建单例
            synchronized (this.singletonObjects) {
                // 尝试从早期单例缓存获取单例对象(未进行属性填充的对象)
                singletonObject = this.earlySingletonObjects.get(beanName);
                if (singletonObject == null && allowEarlyReference) {
                    // 尝试从单例工厂缓存获取单例工厂对象
                    ObjectFactory<?> singletonFactory = this.singletonFactories.get(beanName);
                    if (singletonFactory != null) {
                        // 从单例工厂获取单例对象
                        singletonObject = singletonFactory.getObject();
                        // 早期单例缓存
                        this.earlySingletonObjects.put(beanName, singletonObject);
                        // 后续从早期单例缓存里拿
                        this.singletonFactories.remove(beanName);
                    }
                }
            }
        }
        // 返回获取到的单例对象
        return singletonObject;
    }

    public Object getSingleton(String beanName, ObjectFactory<?> singletonFactory) {
        Assert.notNull(beanName, "Bean name must not be null");
        synchronized (this.singletonObjects) {
            // 尝试从单例对象缓存获取对象
            Object singletonObject = this.singletonObjects.get(beanName);
            if (singletonObject == null) {
                // 单例处于 destruction 状态时,不允许进行单例 bean 创建
                if (this.singletonsCurrentlyInDestruction) {
                    throw new BeanCreationNotAllowedException(beanName,
                            "Singleton bean creation not allowed while singletons of this factory are in destruction " +
                            "(Do not request a bean from a BeanFactory in a destroy method implementation!)");
                }
                if (logger.isDebugEnabled()) {
                    logger.debug("Creating shared instance of singleton bean '" + beanName + "'");
                }
                // 创建过程保护,预防构造器循环依赖
                beforeSingletonCreation(beanName);
                boolean newSingleton = false;
                // suppressedExceptions用于记录异常相关信息
                boolean recordSuppressedExceptions = (this.suppressedExceptions == null);
                if (recordSuppressedExceptions) {
                    this.suppressedExceptions = new LinkedHashSet<>();
                }
                try {
                    // 由单例工厂创建单例对象
                    singletonObject = singletonFactory.getObject();
                    newSingleton = true;
                }
                catch (IllegalStateException ex) {
                    // Has the singleton object implicitly appeared in the meantime ->
                    // if yes, proceed with it since the exception indicates that state.
                    singletonObject = this.singletonObjects.get(beanName);
                    if (singletonObject == null) {
                        throw ex;
                    }
                }
                catch (BeanCreationException ex) {
                    if (recordSuppressedExceptions) {
                        for (Exception suppressedException : this.suppressedExceptions) {
                            ex.addRelatedCause(suppressedException);
                        }
                    }
                    throw ex;
                }
                finally {
                    if (recordSuppressedExceptions) {
                        this.suppressedExceptions = null;
                    }
                    // 创建过程保护,预防构造器循环依赖
                    afterSingletonCreation(beanName);
                }
                if (newSingleton) {
                    // 如果是新的单例对象,缓存到 singletonObjects、registeredSingletons
                    addSingleton(beanName, singletonObject);
                }
            }
            return singletonObject;
        }
    }

addSingleton() 方法

    protected void addSingleton(String beanName, Object singletonObject) {
        synchronized (this.singletonObjects) {
            // 添加到单例对象缓存
            this.singletonObjects.put(beanName, singletonObject);
            // 单例创建完成,不需要了
            this.singletonFactories.remove(beanName);
            this.earlySingletonObjects.remove(beanName);
            // 添加到已经注册的单例对象缓存
            this.registeredSingletons.add(beanName);
        }
    }

总结

实例化大致流程:

三级缓存:

  1. singletonObjects
  2. earlySingletonObjects
  3. singletonFactorys

解决循环依赖:
假设 BeanA 与 BeanB 互相属性依赖

  1. BeanA 实例化前将 BeanName 添加到名为 singletonsCurrentlyInCreation 的 Set 中,然后创建 BeanA 实例
  2. BeanA 实例创建完成后,若允许循环依赖&&单例&& singletonsCurrentlyInCreation 中能找到,则将 BeanA 添加到三级缓存 singletonFactories 中
  3. BeanA 实例填充属性的过程中发现依赖 BeanB , 因此需要去实例化 BeanB
  4. 同样在 BeanB 实例化前将 BeanName 添加到名为 singletonsCurrentlyInCreation 的 Set 中,然后创建 BeanB 实例
  5. 同样在 BeanB 实例创建完成后,若允许循环依赖&&单例&& singletonsCurrentlyInCreation 中能找到,将 BeanB 添加到三级缓存 singletonFactories 中
  6. BeanB 实例填充属性的过程中发现依赖 BeanA , 然后去查找 BeanA ,发现三级缓存中有 BeanA 工厂对象
  7. 从 BeanA 工厂对象中获取到未填充属性的 BeanA 对象存到二级缓存,移除三级缓存,并返回注入给 BeanB 的属性
  8. BeanB 对象创建完成后,从 singletonsCurrentlyInCreation 中删除 BeanName
  9. 将 BeanB 对象添加到 singletonObjects 、registeredSingletons 缓存,并移除二三级缓存中的数据
  10. 返回 BeanB 对象注入 BeanA 实例
  11. BeanA 对象创建完成后,从 singletonsCurrentlyInCreation 中删除 BeanName
  12. 将 BeanA 对象添加到 singletonObjects 、registeredSingletons 缓存,并移除二三级缓存中的数据

简述:
在 BeanA 未填充属性前将其添加到三级缓存。BeanA 填充属性时,去实例化依赖 BeanB 。在 BeanB 发现依赖 BeanA 时,直接从三级缓存中获取未填充属性的 BeanA 。 完成 BeanB 的实例化后,将 BeanB 注入 BeanA 。这样 BeanA 也就可以顺利完成实例化啦。

注:这种算法不适合构造函数循环依赖