SpringBoot源码 - bean的加载(中)

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

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

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

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

点击这个方法进去,可以看到方法体内又有一行代码:

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

真正干活的爷们就是它了。再点进去,可以看到方法实现:

SpringBoot源码 - bean的加载(中)_第1张图片

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

    protected  T doGetBean(
        String name, @Nullable Class 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的地方。下节再讲,喝口酒先~~

你可能感兴趣的:(SpringBoot源码 - bean的加载(中))