乐趣区

关于spring:SpringBoot源码-bean的加载中

精彩的内容来了,各位看官,持续~

接上一节,AbstractApplicationContext 类中的 refresh() 办法,有那么一行不起眼的代码:

// Instantiate all remaining (non-lazy-init) singletons.
finishBeanFactoryInitialization(beanFactory);

就是它,创立 bean 最集中的中央,实例化所有非懒加载的单例。

点击这个办法进去,能够看到办法体内又有一行代码:

// Instantiate all remaining (non-lazy-init) singletons.
beanFactory.preInstantiateSingletons();

真正干活的爷们就是它了。再点进去,能够看到办法实现:

  1. getMergedLocalBeanDefinition(beanName),将 BeanDefinition 的定义进行合并
  2. if (isFactoryBean(beanName)) {……},判断是不是 FactoryBean,拿到 FactoryBean 的实例,判断是否须要提前实例化,须要则通过 getBean 来实例化
  3. getBean(beanName) 一般 bean 的实例化,点进去,来到 doGetBean(),上码:

    protected <T> T doGetBean(String name, @Nullable Class<T> requiredType, @Nullable Object[] args, boolean typeCheckOnly)throws BeansException {
        // 获取实在的 beanName, 因为有的 bean 有别名,FactoryBean 自身创立的时候,传的是 &BeanName
        String beanName = transformedBeanName(name);
        Object beanInstance;
    
        // 从缓存获取单例实例,解决循环依赖和反复创立
        Object sharedInstance = getSingleton(beanName);
        if (sharedInstance != null && args == null) {if (logger.isTraceEnabled()) {if (isSingletonCurrentlyInCreation(beanName)) {logger.trace("……");
                }
                else {logger.trace("……");
                }
            }
            // 解决相似 FactoryBean 这样非凡的 bean 解决
            beanInstance = getObjectForBeanInstance(sharedInstance, name, beanName, null);
        }
    
        else {
            // 原型模式不需解决循环依赖,因为原型 bean 不放缓存,不会提前裸露援用
            if (isPrototypeCurrentlyInCreation(beanName)) {throw new BeanCurrentlyInCreationException(beanName);
            }
    
            // 如果 beanDefinitionMap 未加载有该 bean,则从 parentBeanFactory 查找
            BeanFactory parentBeanFactory = getParentBeanFactory();
            if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {String nameToLookup = originalBeanName(name);
                if (parentBeanFactory instanceof AbstractBeanFactory) {return ((AbstractBeanFactory) parentBeanFactory).doGetBean(nameToLookup, requiredType, args, typeCheckOnly);
                }
                else if (args != null) {return (T) parentBeanFactory.getBean(nameToLookup, args);
                }
                else if (requiredType != null) {return parentBeanFactory.getBean(nameToLookup, requiredType);
                }
                else {return (T) parentBeanFactory.getBean(nameToLookup);
                }
            }
            // 非类型查看的时候,才标记该 bean 已创立
            if (!typeCheckOnly) {markBeanAsCreated(beanName);
            }
    
            StartupStep beanCreation = this.applicationStartup.start("spring.beans.instantiate")                .tag("beanName", name);
            try {if (requiredType != null) {beanCreation.tag("beanType", requiredType::toString);
                }
                RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
                checkMergedBeanDefinition(mbd, beanName, args);
    
                // 以后 bean 依赖的 bean 的创立。String[] dependsOn = mbd.getDependsOn();
                if (dependsOn != null) {for (String dep : dependsOn) {// 不可显式依赖 (@DependOn)
                        if (isDependent(beanName, dep)) {throw new BeanCreationException("……");
                        }
                        // 先创立依赖的 bean,再创立自身本人
                        registerDependentBean(dep, beanName);
                        try {getBean(dep);
                        }
                        catch (NoSuchBeanDefinitionException ex) {throw new BeanCreationException("……");
                        }
                    }
                }
    
                // 单例 bean 创立
                if (mbd.isSingleton()) {sharedInstance = getSingleton(beanName, () -> {
                        try {return createBean(beanName, mbd, args);
                        }
                        catch (BeansException ex) {destroySingleton(beanName);
                            throw ex;
                        }
                    });
                    beanInstance = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
                }
                // 原型 bean 创立
                else if (mbd.isPrototype()) {
                    Object prototypeInstance = null;
                    try {beforePrototypeCreation(beanName);
                        prototypeInstance = createBean(beanName, mbd, args);
                    }
                    finally {afterPrototypeCreation(beanName);
                    }
                    beanInstance = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);
                }
                // 指定 scope 上实例化 bean
                else {String scopeName = mbd.getScope();
                    if (!StringUtils.hasLength(scopeName)) {throw new IllegalStateException("……");
                    }
                    Scope scope = this.scopes.get(scopeName);
                    if (scope == null) {throw new IllegalStateException("……");
                    }
                    try {Object scopedInstance = scope.get(beanName, () -> {beforePrototypeCreation(beanName);
                            try {return createBean(beanName, mbd, args);
                            }
                            finally {afterPrototypeCreation(beanName);
                            }
                        });
                        beanInstance = getObjectForBeanInstance(scopedInstance, name, beanName, mbd);
                    }
                    catch (IllegalStateException ex) {throw new ScopeNotActiveException(beanName, scopeName, ex);
                    }
                }
            }
            catch (BeansException ex) {beanCreation.tag("exception", ex.getClass().toString());
                beanCreation.tag("message", String.valueOf(ex.getMessage()));
                cleanupAfterBeanCreationFailure(beanName);
                throw ex;
            }
            finally {beanCreation.end();
            }
        }
        // 查看理论类型与所需类型是否合乎,不合乎则装换
        return adaptBeanInstance(name, beanInstance, requiredType);
    }

    以上代码中,创立 bean 的中央是:

    createBean(beanName, mbd, args);

    点击该办法进去,还藏有一层:

    doCreateBean(beanName, mbdToUse, args);

    点击该办法进去,就是真正创立 bean 的中央。下节再讲,喝口酒先~~

退出移动版