spring容器之AbstractBeanFactory

上节简单说了FatoryBeanRegistrySupport的方法和以及作用,我们知道该方法主要是对工厂的FactoryBean的一系列的处理,如注册以及后置处理等操作.接下来我们来简单的理解下AbstractBeanFactory的作用和它的家族体系.首先来看它的家族体系如图:

AbstractBeanFactory.png

由图我们直接的看出,AbstractBeanFactory继承了FatoryBeanRegistrySupport的同时,也实现了ConfigurableBeanFactory,可想而知abstractFactoryBean的功能有多强大,这里只是简单的猜测,我们来看它的具体实例.

一. AbstractBeanFactory的作用

  • api里是这样说的,是抽象BeanFactory的基类,同时实现了ConfigurableBeanFactory的SPI,提供了所有的功能
  • 也可以从我们定义的资源中resource中来获取bean的定义.
  • 也提供了单例bean的缓存通过他的爷爷如图中的DefaultSingletonBeanRegistry,同时提供了单例和多例和别名的定义等操作.
  • 上述只是其中的一部分,总之来说它的作用还是挺大的.

二.源码阅读

由于该类方法较多,这里我们简单的说几个重要的方法:

//获取bean
public Object getBean(String name) throws BeansException {
    return doGetBean(name, null, null, false);
}

该方法是实现了BeanFactory接口的getBean()方法,spring里面都是一般这样做的,获取某个东西,实际上封装了一层内部调用如上述代码的doGetBean()方法,那么该方法肯定是我们学习的重要目标了,那么它到底是做了什么我们来看,代码如下:

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

    //该方法去掉别名之后的bean的name,如我这里有一个Student的真实的bean,别名为 Student------>aaStudent
    //Student-------->aaaaStudent,该方法内部循环处理,最终返回Student即可
    final String beanName = transformedBeanName(name);
    Object bean;

    //从上面的去掉别名的beanName拿到后,从缓存中去拿,调用了DefaultSingletonBeanRegistry的getSingleton方法
    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 + "'");
            }
        }
        //获取bean的实例
        bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);
    }

    //这里表明上述的sharedInstance为null
    else {
        //这里分情况来看,spring考虑到了,如果当前的bean已经被创建,获取会失败,可能有别的bean在引用该bean
        if (isPrototypeCurrentlyInCreation(beanName)) {
            throw new BeanCurrentlyInCreationException(beanName);
        }

        //从父工厂中去拿,看是否有该bean的定义
        BeanFactory parentBeanFactory = getParentBeanFactory();
        if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
            //当前类的爸爸中没找到,从爷爷辈去找,直到找到
            String nameToLookup = originalBeanName(name);
            if (parentBeanFactory instanceof AbstractBeanFactory) {
                //调用AbstractBeanFactory的doGetBean方法去获取bean的实例
                return ((AbstractBeanFactory) parentBeanFactory).doGetBean(
                        nameToLookup, requiredType, args, typeCheckOnly);
            }
            //args为首次创建bean的实例时的参数
            else if (args != null) {
                //使用代理的方式去获取bean实例
                return (T) parentBeanFactory.getBean(nameToLookup, args);
            }
            //bean的真实类型
            else if (requiredType != null) {
                return parentBeanFactory.getBean(nameToLookup, requiredType);
            }
            //这里表示我们的args和requiredType都为null,直接通过得到的bean的名字去获取实例
            else {
                return (T) parentBeanFactory.getBean(nameToLookup);
            }
        }
        //对bean的真实类型检查,在检查之前不可使用该bean
        if (!typeCheckOnly) {
            //对已经创建完的bean的实例做标记,如:已完成创建
            markBeanAsCreated(beanName);
        }

        try {
            //合并父子bean的定义
            final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
            //检查合并之后的bean的定义,必要时抛异常
            checkMergedBeanDefinition(mbd, beanName, args);

            //先初始化当前bean所依赖的bean
            //如:我的订单类需要商品类,此刻spring会先初始化商品类,大概就是这样的
            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 + "'");
                    }
                    //给当前bean注册一个依赖bean
                    registerDependentBean(dep, beanName);
                    try {

                        getBean(dep);
                    }
                    catch (NoSuchBeanDefinitionException ex) {
                        throw new BeanCreationException(mbd.getResourceDescription(), beanName,
                                "'" + beanName + "' depends on missing bean '" + dep + "'", ex);
                    }
                }
            }

            // Create bean instance.
            //创建bean实例
            //单例的情况下
            if (mbd.isSingleton()) {
                //从缓存(singletonObjects)中去拿
                sharedInstance = getSingleton(beanName, () -> {
                    try {
                        return createBean(beanName, mbd, args);
                    }
                    catch (BeansException ex) {
                        //最后从缓存中移除对应的实例原因有:
                        //1.每当有bean在创建时,允许循环参考来解析对应的beanDefinition
                        //2.删除临时引用该bean的bean
                        destroySingleton(beanName);
                        throw ex;
                    }
                });

                bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
            }
            //多例的情况下:
            else if (mbd.isPrototype()) {

                Object prototypeInstance = null;
                try {
                    beforePrototypeCreation(beanName);
                    prototypeInstance = createBean(beanName, mbd, args);
                }
                finally {
                    //创建完bean的处理
                    afterPrototypeCreation(beanName);
                }
                bean = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);
            }

            else {
                //获取bean的作用域
                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;
        }
    }

    //检查类型与实际的bean的是否匹配
    if (requiredType != null && !requiredType.isInstance(bean)) {
        try {
            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());
        }
    }
    return (T) bean;
}

上面代码是spring如何获取bean的过程,实际最核心的是createBean() 方法,该方法真正的创建bean的过程

/**
 * 该方法是AbstractAutowireCapableBeanFactory中的实现方法
 *
 */
protected Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
        throws BeanCreationException {

    if (logger.isTraceEnabled()) {
        logger.trace("Creating instance of bean '" + beanName + "'");
    }
    RootBeanDefinition mbdToUse = mbd;

    // 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.
    //解析bean的class
    //1.这里当解析的resolvedClass和mbd.hasBeanClass()为falsembd.getBeanClassName()同时成立时
    //2.这里需要我们new一个合并的beanDefinition类,同时设置class类型
    Class<?> resolvedClass = resolveBeanClass(mbd, beanName);
    if (resolvedClass != null && !mbd.hasBeanClass() && mbd.getBeanClassName() != null) {
        mbdToUse = new RootBeanDefinition(mbd);
        mbdToUse.setBeanClass(resolvedClass);
    }

    //覆盖了RootBeanDefinition的prepareMethodOverrides方法
    try {
        mbdToUse.prepareMethodOverrides();
    }
    catch (BeanDefinitionValidationException ex) {
        throw new BeanDefinitionStoreException(mbdToUse.getResourceDescription(),
                beanName, "Validation of method overrides failed", ex);
    }

    try {
        //获取一个解析之后的代理bean的实例,而不是真正的bean实例
        Object bean = resolveBeforeInstantiation(beanName, mbdToUse);
        if (bean != null) {
            return bean;
        }
    }
    catch (Throwable ex) {
        throw new BeanCreationException(mbdToUse.getResourceDescription(), beanName,
                "BeanPostProcessor before instantiation of bean failed", ex);
    }

    try {
        //这里才是真正的执行创建bean的方法
        Object beanInstance = doCreateBean(beanName, mbdToUse, args);
        if (logger.isTraceEnabled()) {
            logger.trace("Finished creating instance of bean '" + beanName + "'");
        }
        return beanInstance;
    }
    catch (BeanCreationException | ImplicitlyAppearedSingletonException ex) {
        // A previously detected exception with proper bean creation context already,
        // or illegal singleton state to be communicated up to DefaultSingletonBeanRegistry.
        throw ex;
    }
    catch (Throwable ex) {
        throw new BeanCreationException(
                mbdToUse.getResourceDescription(), beanName, "Unexpected exception during bean creation", ex);
    }
}

再来看真正的创建bean的方法:

/**
 * 该方法是真正的创建bean的方法
 * @param beanName 要创建bean的名称
 * @param mbd 定义bean的beanDefinition文件
 * @param args 创建bean时,构造方法所需的参数或者是调用bean工厂时来创建bean所需的参数
 * @return 完成创建之后的bean的实例
 * @throws BeanCreationException
 */
protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final @Nullable Object[] args)
        throws BeanCreationException {

    //实例化bean的过程
    BeanWrapper instanceWrapper = null;
    //如果是单例,从factoryBeanInstanceCache中移除相应的bean实例
    if (mbd.isSingleton()) {
        instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
    }
    //创建实例
    if (instanceWrapper == null) {
        instanceWrapper = createBeanInstance(beanName, mbd, args);
    }
    //获取封装实例
    final Object bean = instanceWrapper.getWrappedInstance();
    //获取对应实例的class类型
    Class<?> beanType = instanceWrapper.getWrappedClass();
    if (beanType != NullBean.class) {
        //将获取到的bean类型赋值给mbd的resolvedTargetType
        //resolvedTargetType用来保存真实类型bean的类型
        mbd.resolvedTargetType = beanType;
    }

    // Allow post-processors to modify the merged bean definition.
    //允许后置处理修改mbd
    synchronized (mbd.postProcessingLock) {
        //postProcessed默认为false,故不能修改,这里取反表示可以修改
        if (!mbd.postProcessed) {
            try {
                //对bean进行后置处理
                applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
            }
            catch (Throwable ex) {
                throw new BeanCreationException(mbd.getResourceDescription(), beanName,
                        "Post-processing of merged bean definition failed", ex);
            }
            mbd.postProcessed = true;
        }
    }

    //处理循环引用和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");
        }
        addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
    }

    //初始化bean实例
    Object exposedObject = bean;
    try {
        //给bean的实例填充属性
        populateBean(beanName, mbd, instanceWrapper);
        //初始化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);
        }
    }
    //引用问题处理,这里先暴露早期单例引用的bean
    if (earlySingletonExposure) {
        //从缓存注册中获取,这里不允许早期引用的创建
        Object earlySingletonReference = getSingleton(beanName, false);
        if (earlySingletonReference != null) {
            if (exposedObject == bean) {
                exposedObject = earlySingletonReference;
            }
            else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) {
                String[] dependentBeans = getDependentBeans(beanName);
                Set<String> actualDependentBeans = new LinkedHashSet<>(dependentBeans.length);
                for (String dependentBean : dependentBeans) {
                    if (!removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) {
                        actualDependentBeans.add(dependentBean);
                    }
                }
                if (!actualDependentBeans.isEmpty()) {
                    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.");
                }
            }
        }
    }

    //注册bean
    try {
        registerDisposableBeanIfNecessary(beanName, bean, mbd);
    }
    catch (BeanDefinitionValidationException ex) {
        throw new BeanCreationException(
                mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex);
    }

    return exposedObject;
}

上述就是spring创建bean的过程,实际上真正创建bean的方法在doCreateBean这里,关于spring的如何获取bean的过程在后续再说.

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 201,681评论 5 474
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 84,710评论 2 377
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 148,623评论 0 334
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,202评论 1 272
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,232评论 5 363
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,368评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,795评论 3 393
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,461评论 0 256
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,647评论 1 295
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,476评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,525评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,226评论 3 318
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,785评论 3 303
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,857评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,090评论 1 258
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,647评论 2 348
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,215评论 2 341

推荐阅读更多精彩内容