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 doGetBean(final String name, @Nullable final Class 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 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的过程在后续再说.

你可能感兴趣的:(spring容器之AbstractBeanFactory)