Spring源码解读

IOC容器
BeanFactory及其实现类


图片.png
图片.png

BeanFactory是根级容器定义,规范了Ioc容器应该拥有哪些能力。
ApplicationContext是提供给使用者的接口,其继承于BeanFactory,并提供了更多的能力。Spring容器部分,提供了很多接口来定义不同容器的规范,具体实现类可以通过实现多个接口来提供相应的能力。

从new AnnotationConfigApplicationContext(BootConfig.class);入手,看看Spring 容器整体上是怎样在初始化

StartupStep contextRefresh = this.applicationStartup.start("spring.context.refresh");

            // Prepare this context for refreshing.
            // 容器刷新前的准备工作:设置容器启动状态,加载一些资源,重置一些监听器等
            prepareRefresh();

            // Tell the subclass to refresh the internal bean factory.
            // 生成一个新的beanFactory[模板方法模式,调用子类方法刷新beanFactory]
            // 如果beanFactory存在,则销毁其中的bean,并销毁beanFactory
            // 创建一个新的beanFactory
            // 设置一些bean初始化的属性 overriding及circleReference
            // 加载bean的定义
            ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();

            // Prepare the bean factory for use in this context.
            // 给beanFactory设置一些附加属性,例如一些监听器等
            prepareBeanFactory(beanFactory);

            try {
                // Allows post-processing of the bean factory in context subclasses.
                // 子类容器bean factory创建后置处理
                // 添加一些监听器等
                postProcessBeanFactory(beanFactory);

                StartupStep beanPostProcess = this.applicationStartup.start("spring.context.beans.post-process");
                // Invoke factory processors registered as beans in the context.
                // beanFactory后置处理器
                // 执行容器中注册的bean factory相关的一些处理器
                invokeBeanFactoryPostProcessors(beanFactory);

                // Register bean processors that intercept bean creation.
                // 注册bean的后置处理器[bean创建的拦截器]到容器中
                registerBeanPostProcessors(beanFactory);
                beanPostProcess.end();

                // Initialize message source for this context.
                // 初始化国际化资源等
                initMessageSource();

                // Initialize event multicaster for this context.
                // 初始化事件广播
                initApplicationEventMulticaster();

                // Initialize other special beans in specific context subclasses.
                // 初始化特殊容器的特殊bean(模板方法模式,由子类容器决定),比如UI初始化
                onRefresh();

                // Check for listener beans and register them.
                // 注册bean的监听器
                registerListeners();

                // Instantiate all remaining (non-lazy-init) singletons.
                // 初始化非懒加载单例bean
                finishBeanFactoryInitialization(beanFactory);

                // Last step: publish corresponding event.
                // 初始化完成,发布一些事件
                finishRefresh();
             } catch(...) ...

SpringIOC容器初始化比较繁琐,需要做很多的工作,注释中我添加了对当前步骤所做事情的的描述。
简单来说,步骤如下:

  • 1.初始化BeanFactory(这一步会加载Bean的配置到BeanDefinition中,并用ConcurrentHashMap存储起来)
  • 2.给BeanFactory设置一些监听器
  • 3.注册bean的后置处理器(BeanPostProcessor)
  • 4.初始化国际化资源
  • 5.初始化应用事件广播
  • 6.初始化一些特殊bean
  • 7.注册Bean的监听器
  • 8.初始化非懒加载单例bean
  • 9.容器刷新完成,发布一些事件
  • 10.其他善后工作

接着从finishBeanFactoryInitilization方法入手,看看bean的初始化步骤

DefaultSingleBeanRegistry中的一些核心方法

/**
     * Return an instance, which may be shared or independent, of the specified bean.
     * @param name the name of the bean to retrieve
     * @param requiredType the required type of the bean to retrieve
     * @param args arguments to use when creating a bean instance using explicit arguments
     * (only applied when creating a new instance as opposed to retrieving an existing one)
     * @param typeCheckOnly whether the instance is obtained for a type check,
     * not for actual use
     * @return an instance of the bean
     * @throws BeansException if the bean could not be created
     */
    @SuppressWarnings("unchecked")
    protected <T> T doGetBean(
            String name, @Nullable Class<T> requiredType, @Nullable Object[] args, boolean typeCheckOnly)
            throws BeansException {

        String beanName = transformedBeanName(name);
        Object beanInstance;

        // Eagerly check singleton cache for manually registered singletons.
        // 检查单例缓存是否有手动注册的单例。
        // 提前暴露的bean在解决循环依赖时可以在这里使用。
        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 实例的对象,如果是 FactoryBean,则是 bean 实例本身或其创建的对象
            beanInstance = getObjectForBeanInstance(sharedInstance, name, beanName, null);
        }

        else {
            // Fail if we're already creating this bean instance:
            // We're assumably within a circular reference.
            if (isPrototypeCurrentlyInCreation(beanName)) {
                throw new BeanCurrentlyInCreationException(beanName);
            }

            // Check if bean definition exists in this factory.
            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 if (requiredType != null) {
                    // No args -> delegate to standard getBean method.
                    return parentBeanFactory.getBean(nameToLookup, requiredType);
                }
                else {
                    return (T) parentBeanFactory.getBean(nameToLookup);
                }
            }

            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);

                // Guarantee initialization of beans that the current bean depends on.
                // 检查bean依赖的其他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 + "'");
                        }
                        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.
                // 创建实例
                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;
                        }
                    });
                    beanInstance = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
                }

                else if (mbd.isPrototype()) {
                    // It's a prototype -> create a new instance.
                    // prototype直接创建一个对象
                    Object prototypeInstance = null;
                    try {
                        // prototype bean创建前置处理
                        beforePrototypeCreation(beanName);
                        prototypeInstance = createBean(beanName, mbd, args);
                    }
                    finally {
                        // 执行属性创建后的逻辑:清空正在处理的bean属性
                        afterPrototypeCreation(beanName);
                    }
                    beanInstance = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);
                }

                else {
                    String scopeName = mbd.getScope();
                    if (!StringUtils.hasLength(scopeName)) {
                        throw new IllegalStateException("No scope name defined for bean ´" + beanName + "'");
                    }
                    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 {
                                // 创建bean
                                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);
    }

/**
     * Return the (raw) singleton object registered under the given name.
     * <p>Checks already instantiated singletons and also allows for an early
     * reference to a currently created singleton (resolving a circular reference).
     * @param beanName the name of the bean to look for
     * @param allowEarlyReference whether early references should be created or not
     * @return the registered singleton object, or {@code null} if none found
     */
    @Nullable
    protected Object getSingleton(String beanName, boolean allowEarlyReference) {
        // Quick check for existing instance without full singleton lock
        // 从单例池中获取bean
        Object singletonObject = this.singletonObjects.get(beanName);
        if (singletonObject == null && isSingletonCurrentlyInCreation(beanName)) {
            // 从二级缓存中获取bean
            singletonObject = this.earlySingletonObjects.get(beanName);
            if (singletonObject == null && allowEarlyReference) {
                // 单例池加锁
                synchronized (this.singletonObjects) {
                    // Consistent creation of early reference within full singleton lock
                    // 再次从单例池中获取
                    singletonObject = this.singletonObjects.get(beanName);
                    if (singletonObject == null) {
                        // 再次从二级缓存中获取
                        singletonObject = this.earlySingletonObjects.get(beanName);
                        if (singletonObject == null) {
                            // 三级缓存中获取当前bean的ObjectFactory
                            ObjectFactory<?> singletonFactory = this.singletonFactories.get(beanName);
                            if (singletonFactory != null) {
                                // 从工厂获取bean
                                singletonObject = singletonFactory.getObject();
                                // 放入二级缓存
                                this.earlySingletonObjects.put(beanName, singletonObject);
                                // 三级缓存移除ObjectFactory
                                this.singletonFactories.remove(beanName);
                            }
                        }
                    }
                }
            }
        }
        return singletonObject;
    }

/**
     * Actually create the specified bean. Pre-creation processing has already happened
     * at this point, e.g. checking {@code postProcessBeforeInstantiation} callbacks.
     * <p>Differentiates between default bean instantiation, use of a
     * factory method, and autowiring a constructor.
     * @param beanName the name of the bean
     * @param mbd the merged bean definition for the bean
     * @param args explicit arguments to use for constructor or factory method invocation
     * @return a new instance of the bean
     * @throws BeanCreationException if the bean could not be created
     * @see #instantiateBean
     * @see #instantiateUsingFactoryMethod
     * @see #autowireConstructor
     */
    protected Object doCreateBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
            throws BeanCreationException {

        // Instantiate the bean.
        BeanWrapper instanceWrapper = null;
        if (mbd.isSingleton()) {
            // 因为是单例,所以只需要被初始化一次,这里移除的同时,拿到FactoryBean供本次使用
            instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
        }
        if (instanceWrapper == null) {
            instanceWrapper = createBeanInstance(beanName, mbd, args);
        }
        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;
            }
        }

        // Eagerly cache singletons to be able to resolve circular references
        // even when triggered by lifecycle interfaces like BeanFactoryAware.
        // 单例 && 允许循环依赖 && 是创建中的单例
        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");
            }
            // 创建ObjectFactory,并放入三级缓存中,提供一个可以提前访问的方式
            // 放入三级缓存的实际是一个ObjectFactory,直到被调用getObject时时才会触发getEarlyBeanReference中的代码
            // getEarlyBeanReference中会执行SmartInstantiationAwareBeanPostProcessor(简称bp)的getEarlyBeanReference方法
            // 此时如果需要被代理,会执行bp会执行wrapIfNecessary(),然后执行createProxy()来生成代理
            // 也即是说这个早期引用如果需要被代理,返回的已经是代理后对象了,这就保证了依赖不会因代理问题而出错。
            // 为什么又要引入三级缓存来存入ObjectFactory呢,目的是getObject延迟执行
            // 也即是getObject调用后再执行getEarlyBeanReference中的代码,以控制bean的生命周期顺序。
            addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
        }

        // Initialize the bean instance.
        Object exposedObject = bean;
        try {
            // 设置bean属性
            populateBean(beanName, mbd, instanceWrapper);
            // 初始化bean,执行一些Aware及BeanPostProcessor、initMethod等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) {
            // 尝试从二级缓存中取,取得到对象,说明是当前对象存在循环引用。
            // 因为这里当前对象尚在创建中,创建这个对象完成之前提前暴露了一个引用在三级缓存中,而这里到了二级缓存,必然是别的bean想从beanFactory中去获取当前bean。
            Object earlySingletonReference = getSingleton(beanName, false);
            if (earlySingletonReference != null) {
                if (exposedObject == bean) {
                    // 引用相同,说明没有被代理,此时获取到的还是原来的,直接返回
                    // 为什么需要比较呢,因为后置处理器是可以改变bean的。
                    exposedObject = earlySingletonReference;
                }
                else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) {
                    // 获取依赖于当前bean的那些bean
                    String[] dependentBeans = getDependentBeans(beanName);
                    Set<String> actualDependentBeans = new LinkedHashSet<>(dependentBeans.length);
                    for (String dependentBean : dependentBeans) {
                        // 移除已创建的,因为这里只需要验证是否有尚未创建的依赖,
                        // 已经创建完的bean依赖于当前bean,这里需要把他们移除
                        if (!removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) {
                            // 已经创建好的bean中包含依赖于当前bean的bean
                            actualDependentBeans.add(dependentBean);
                        }
                    }
                    if (!actualDependentBeans.isEmpty()) {
                        // 当前单例bean被他人引用,并且其他bean还是已完成创建的,当前bean又被后置处理器改变了,这是不允许的
                        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 " +
                                "'getBeanNamesForType' with the 'allowEagerInit' flag turned off, for example.");
                    }
                }
            }
        }

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

        return exposedObject;
    }

简单来说
** doGetBean **步骤如下:

  • 1.尝试获取单例bean,获取顺序为:1级缓存(singletonObjects),2级缓存(earlySingletonObjects),3级缓存(singletonFactories)
  • 2.从1中没有取到,执行createBean,最终会调用getSingleton

getSingleton步骤如下:

  • 创建前的处理
  • 创建bean(singletonFactory.getObject()),从doGetBean中可以看到,getObject实质上执行了createBean,createBean中核心代码是调用doCreateBean
  • 后置处理
  • 注册bean到单例池,移除二三级缓存

doCreateBean步骤如下:

  • 1.实例化bean
  • 2.新建一个ObjectFactory放入singletonFactory
    这一步很重要,放入的这个singletonFactory将会做很多事情。暴露一个ObjectFactory在三级缓存中,如果存在循环依赖,其他依赖于该对象的bean可以从三级缓存中获取到。获取的同时,会判断是否需要代理,循环依赖时aop的代理就是在getObject的过程中生成的,最终返回一个代理的对象。
    假如不存在循环引用的问题,在getSingleton后续步骤,也会将这个singleObject放入一级缓存,同时删除二三级缓存中的bean与objectFactory(不存在循环引用,二级缓存实质上不会有当前bean)
  • 3.设置属性
  • 4.执行初始化方法:
    • 4.1 执行aware相关的钩子函数,
    • 4.2 beanPostProcessor前置处理
    • 4.3 InitMethod
    • 4.4 beanPostProcessor后置处理
      当不存在循环依赖时,这一步AbstractAutoProxyCreator.postProcessAfterInitialization中执行wrapIfNecessary()处理AOP的代理。
  • 如果是循环引用的bean,则判断是否有已完成实例化但使用了代理前引用的对象,如果存在,则会报错
  • 放入一次性缓存,供销毁时使用(单例bean,所以只有一个,同时也只会使用一次,容器关闭时会销毁这个bean)

AOP源码:

图片.png

关于AOP代理生成时机,在上面IOCbean创建部分已充分说明,此处强调一下如何选择代理方式:

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

推荐阅读更多精彩内容