Spring IOC容器加载实例化bean流程

Spring IOC加载实例化bean流程概要

Spring启动流程主要是调用AbstractApplicationContext的refresh方法完成容器的一系列初始化操作,其中有两个子流程在加载实例化bean做了很多工作,
1.obtainFreshBeanFactory方法初始化BeanFactory并加载bean定义
2.finishBeanFactoryInitialization方法完成对非抽象的&&单例的&&非懒加载的bean进行实例化

    public void refresh() throws BeansException, IllegalStateException {
        synchronized (this.startupShutdownMonitor) {
            
            // 容器刷新预处理,调用initPropertySources与validateRequiredProperties进行环境属性设置与校验
            prepareRefresh();

            // 初始化beanfactory,创建DefaultListableBeanFactory,加载bean定义
            ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();

            // beanfactory预处理工作,添加设置bean类加载器,bean后置处理器,,注册beanfactory相关依赖等
            prepareBeanFactory(beanFactory);

            try {
                // beanfactory准备工作后置处理工作
                postProcessBeanFactory(beanFactory);

                // 激活beanfactory后置处理器,设置注解解析器
                invokeBeanFactoryPostProcessors(beanFactory);

                // 注册bean后置处理器
                registerBeanPostProcessors(beanFactory);

                // 初始化国际化资源处理器
                initMessageSource();

                // 创建事件多播器
                initApplicationEventMulticaster();

                // 刷新特定子类bean
                onRefresh();

                // 事件监听器注册到多播器
                registerListeners();

                // 实例化剩余的单例beanfactory,创建bean,从bean定义中判断出非抽象的&&单例的&&非懒加载的bean进行实例化
                finishBeanFactoryInitialization(beanFactory);

                // 完成刷新过程
                finishRefresh();
            }

            catch (BeansException ex) {
                if (logger.isWarnEnabled()) {
                    logger.warn("Exception encountered during context initialization - " +
                            "cancelling refresh attempt: " + ex);
                }

                // Destroy already created singletons to avoid dangling resources.
                destroyBeans();

                // Reset 'active' flag.
                cancelRefresh(ex);

                // Propagate exception to caller.
                throw ex;
            }

            finally {
                // Reset common introspection caches in Spring's core, since we
                // might not ever need metadata for singleton beans anymore...
                resetCommonCaches();
            }
        }
    }

Bean定义的加载

obtainFreshBeanFactory方法入口可以找到refreshBeanFactory方法,loadBeanDefinition加载bean定义,如通过xml或者注解装载成BeanDefinition对象

    protected final void refreshBeanFactory() throws BeansException {
        if (hasBeanFactory()) {
            destroyBeans();
            closeBeanFactory();
        }
        try {
            DefaultListableBeanFactory beanFactory = createBeanFactory();
            beanFactory.setSerializationId(getId());
            customizeBeanFactory(beanFactory);
                        //在此处进行bean定义的加载
            loadBeanDefinitions(beanFactory);
            synchronized (this.beanFactoryMonitor) {
                this.beanFactory = beanFactory;
            }
        }
        catch (IOException ex) {
            throw new ApplicationContextException("I/O error parsing bean definition source for " + getDisplayName(), ex);
        }
    }

获取Bean实例

1.检查单例缓存池中是否有对应实例(实例可能未完全实例化完),有则通过工厂bean缓存池或对应工厂bean方法获取;
2.没有则递归向上寻找父工厂获取bean实例;
3.再没有获取bean实例则开始创建bean实例,首先先获取所有对应的依赖bean实例(没有则实例化)
4.调用createBean方法完成对自身的创建并返回自身bean实例

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

        //获取bean的名称
        final String beanName = transformedBeanName(name);
        Object bean;

        //检查单例对象缓存池或实例工厂是否有对应的实例
        //创建单例bean的时候依赖注入存在循环依赖问题
        //Spring创建bean会将bean的ObjectFactory加入到缓存中,下一个创建依赖上一个bean则直接使用
        Object sharedInstance = getSingleton(beanName);
        if (sharedInstance != null && args == null) {
            if (logger.isDebugEnabled()) {
                if (isSingletonCurrentlyInCreation(beanName)) {
                    logger.debug("Returning eagerly cached instance of singleton bean '" + beanName +
                            "' that is not fully initialized yet - a consequence of a circular reference");
                }
                else {
                    logger.debug("Returning cached instance of singleton bean '" + beanName + "'");
                }
            }
            //通过FactoryBean中获取bean,使用指定方法返回实例,获取bean的过程做后置处理
            bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);
        }

        else {
            //只有单例的情况下才会尝试
            //原型模式下 存在下列情况
            //A依赖B B依赖A  当依赖注入的时候 当A未创建完 对于B的创建再次返回创建A 形成循环依赖
            if (isPrototypeCurrentlyInCreation(beanName)) {
                throw new BeanCurrentlyInCreationException(beanName);
            }

            // Check if bean definition exists in this factory.
            // 判断bean定义是否存在在当前工厂,没有则向父工厂递归寻找
            BeanFactory parentBeanFactory = getParentBeanFactory();
            if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
                // Not found -> check parent.
                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 {
                    // No args -> delegate to standard getBean method.
                    return parentBeanFactory.getBean(nameToLookup, requiredType);
                }
            }

            if (!typeCheckOnly) {
                markBeanAsCreated(beanName);
            }

            try {
                final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
                checkMergedBeanDefinition(mbd, beanName, args);

                //对当前依赖的bean进行初始化
                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依赖关系
                        registerDependentBean(dep, beanName);
                        try {
                            //对依赖bean
                            getBean(dep);
                        }
                        catch (NoSuchBeanDefinitionException ex) {
                            throw new BeanCreationException(mbd.getResourceDescription(), beanName,
                                    "'" + beanName + "' depends on missing bean '" + dep + "'", ex);
                        }
                    }
                }

                // 实例化mbd所有依赖对象之后,开始实例化mbd
                if (mbd.isSingleton()) {
                    sharedInstance = getSingleton(beanName, () -> {
                        try {
                            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;
                        }
                    });
                    bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
                }

                else if (mbd.isPrototype()) {
                    // It's a prototype -> create a new instance.
                    Object prototypeInstance = null;
                    try {
                        beforePrototypeCreation(beanName);
                        prototypeInstance = createBean(beanName, mbd, args);
                    }
                    finally {
                        afterPrototypeCreation(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.
        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.isDebugEnabled()) {
                    logger.debug("Failed to convert bean '" + name + "' to required type '" +
                            ClassUtils.getQualifiedName(requiredType) + "'", ex);
                }
                throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
            }
        }
        return (T) bean;
    }

循环依赖

在bean实例化过程中,存在着循环依赖问题(即A->B B->A),Spring只对singleton模式下setter注入方式解决循环依赖问题,其他情况则抛出BeanCurrentlyInCreationException。

spring对于singleton模式下setter注入方式下循环依赖问题做了三层缓存:

singletonFactories一级缓存,存放ObjectFactory
earlySingletonObjects二级缓存,单例对象缓存池,存在初始化中间状态,用于检测循环依赖
singletonObjects三级缓存,单例对象缓存池,存放已经实例化的单例对象
singletonsCurrentlyInCreation保存正在创建实例化的单例bean名称

在单例对象没有完全初始化前,singletonsCurrentlyInCreation会一直保存bean名称,beforeSingletonCreation方法往singletonsCurrentlyInCreation添加bean名称。

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();
                        //earlySingletonObjects与singletonFactories互斥
                        this.earlySingletonObjects.put(beanName, singletonObject);
                        this.singletonFactories.remove(beanName);
                    }
                }
            }
        }
        return singletonObject;
    }
public Object getSingleton(String beanName, ObjectFactory singletonFactory) {
        Assert.notNull(beanName, "'beanName' must not be null");
        synchronized (this.singletonObjects) {
            Object singletonObject = this.singletonObjects.get(beanName);
            if (singletonObject == null) {
                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 + "'");
                }
                //添加中间状态,singletonsCurrentlyInCreation保存bean名称
                beforeSingletonCreation(beanName);
                boolean newSingleton = false;
                boolean recordSuppressedExceptions = (this.suppressedExceptions == null);
                if (recordSuppressedExceptions) {
                    this.suppressedExceptions = new LinkedHashSet();
                }
                try {
                    //singletonFactory获取单例bean
                    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.
                    //从单例缓存池获取bean
                    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;
                    }
                    //移除中间状态,singletonsCurrentlyInCreation移除bean名称
                    afterSingletonCreation(beanName);
                }
                if (newSingleton) {
                    addSingleton(beanName, singletonObject);
                }
            }
            return (singletonObject != NULL_OBJECT ? singletonObject : null);
        }
    }

创建bean实例

1.createBeanInstance创建bean实例,底层调用反射机制或者cglib完成接口对象或类对象的创建,创建策略包括工厂方法、构造函数初始化、简单初始化;
2.检测是否存在单例循环依赖
3.populateBean方法完成属性值注入填充,进行依赖注入,底层调用autowireByName方法与autowireByType方法对注解@Autowire修饰的属性进行注入,最终调用applyPropertyValues方法匹配BeanWrapper的getPropertyDescriptors完成属性值设置;
4.initializeBean完成bean初始化,底层依次调用invokeAwareMethods方法(Aware子类实现方法,例如BeanNameAwareBeanFactoryAware)、applyBeanPostProcessorsBeforeInitialization方法(BeanPostProcessor后置处理器初始化前postProcessBeforeInstantiation方法)、invokeInitMethods方法(InitializingBean接口的afterPropertiesSet方法)、applyBeanPostProcessorsAfterInitialization方法(BeanPostProcessor后置处理器初始化后postProcessAfterInitialization方法)。
5.返回创建完的bean实例

protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final @Nullable Object[] args)
            throws BeanCreationException {

        // Instantiate the bean.
        BeanWrapper instanceWrapper = null;
        if (mbd.isSingleton()) {
            instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
        }
        if (instanceWrapper == null) {
            //创建bean实例
            //工厂方法,构造函数初始化,简单初始化
            instanceWrapper = createBeanInstance(beanName, mbd, args);
        }
        final Object bean = instanceWrapper.getWrappedInstance();
        Class beanType = instanceWrapper.getWrappedClass();
        if (beanType != NullBean.class) {
            mbd.resolvedTargetType = beanType;
        }

        // Allow post-processors to modify the merged bean definition.
        synchronized (mbd.postProcessingLock) {
            if (!mbd.postProcessed) {
                try {
                    applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
                }
                catch (Throwable ex) {
                    throw new BeanCreationException(mbd.getResourceDescription(), beanName,
                            "Post-processing of merged bean definition failed", ex);
                }
                mbd.postProcessed = true;
            }
        }
        
        //检测循环依赖
        boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences &&
                isSingletonCurrentlyInCreation(beanName));
        if (earlySingletonExposure) {
            if (logger.isDebugEnabled()) {
                logger.debug("Eagerly caching bean '" + beanName +
                        "' to allow for resolving potential circular references");
            }
            //在bean初始化完成前,将ObjectFactory放进singletonFactories,避免循环依赖
            addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
        }

        // Initialize the bean instance.
        Object exposedObject = bean;
        try {
            //注入属性值
            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);
            }
        }

        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);
                        }
                    }
                    //遍历获取所有依赖的bean
                    //actualDependentBeans不为空 表示当前bean创建后依赖的bean没有被全部创建完,存在循环依赖
                    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.");
                    }
                }
            }
        }

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

        return exposedObject;
    }

流程总结

整个Spring IOC容器加载实例化bean的流程大概如图所示


Spring IOC容器加载实例化bean流程_第1张图片
Spring加载实例化bean流程图.png

你可能感兴趣的:(Spring IOC容器加载实例化bean流程)