spring源码解析-ApplicationContext 启动流程(3)- 执行 AbstractApplicationContext#finishBeanFactoryInitialization(ConfigurableListableBeanFactory) 方法

直接看源码

    /**
     * 
     * 完成所有单实例 bean 的实例化
     * Finish the initialization of this context‘s bean factory,
     * initializing all remaining singleton beans.
     */
    protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {
        // Initialize conversion service for this context.
        if (beanFactory.containsBean(CONVERSION_SERVICE_BEAN_NAME) &&
                beanFactory.isTypeMatch(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class)) {
            beanFactory.setConversionService(
                    beanFactory.getBean(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class));
        }

        // 注册一个默认的值解析器
        // Register a default embedded value resolver if no bean post-processor
        // (such as a PropertyPlaceholderConfigurer bean) registered any before:
        // at this point, primarily for resolution in annotation attribute values.
        if (!beanFactory.hasEmbeddedValueResolver()) {
            beanFactory.addEmbeddedValueResolver(strVal -> getEnvironment().resolvePlaceholders(strVal));
        }

        // Initialize LoadTimeWeaverAware beans early to allow for registering their transformers early.
        String[] weaverAwareNames = beanFactory.getBeanNamesForType(LoadTimeWeaverAware.class, false, false);
        for (String weaverAwareName : weaverAwareNames) {
            getBean(weaverAwareName);
        }

        // Stop using the temporary ClassLoader for type matching.
        beanFactory.setTempClassLoader(null);

        // Allow for caching all bean definition metadata, not expecting further changes.
        beanFactory.freezeConfiguration();

        //实例化所有剩余的的单例 bean
        // Instantiate all remaining (non-lazy-init) singletons.
        beanFactory.preInstantiateSingletons();
    }
finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) 执行目的是为了完成单实例 bean 实例化,它主要会按序执行以下几步
  1. 注册一个默认的值解析器 StringValueResolver 负责解析配置文件中的键值对
  2. 初始化所有 LoadTimeWeaverAware
  3. 实例化所有剩余的的单例 bean //beanFactory.preInstantiateSingletons();

进入 beanFactory.preInstantiateSingletons();

    @Override
    public void preInstantiateSingletons() throws BeansException {
        if (logger.isTraceEnabled()) {
            logger.trace("Pre-instantiating singletons in " + this);
        }

        // Iterate over a copy to allow for init methods which in turn register new bean definitions.
        // While this may not be part of the regular factory bootstrap, it does otherwise work fine.
        List<String> beanNames = new ArrayList<>(this.beanDefinitionNames);

        //初始化所有非延迟加载的单实例 bean, 核心调用方法为 AbstractBeanFactory#getBean(String name)
        // Trigger initialization of all non-lazy singleton beans...
        for (String beanName : beanNames) {
            //首先合并 BeanDefinition,在基于 xml 配置中,有一种 parent bean 的写法,
            // 在基于注解式驱动中,这个方法已经无意义,和调用 getBeanDefinition(String beanName) 返回结果一样
            RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);

            //实例化的三个条件: 非抽象,单例,非懒加载
            if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {
                //判断当前 bean 是不是实现了 FactoryBean 接口来做不同的操作
                if (isFactoryBean(beanName)) {
                    //如果当前 bean 实现了FactoryBean 接口,这个 bean 的名称是 & + beanName
                    Object bean = getBean(FACTORY_BEAN_PREFIX + beanName);
                    if (bean instanceof FactoryBean) {
                        FactoryBean<?> factory = (FactoryBean<?>) bean;
                        boolean isEagerInit;
                        if (System.getSecurityManager() != null && factory instanceof SmartFactoryBean) {
                            isEagerInit = AccessController.doPrivileged(
                                    (PrivilegedAction<Boolean>) ((SmartFactoryBean<?>) factory)::isEagerInit,
                                    getAccessControlContext());
                        }
                        else {
                            isEagerInit = (factory instanceof SmartFactoryBean &&
                                    ((SmartFactoryBean<?>) factory).isEagerInit());
                        }
                        if (isEagerInit) {
                            getBean(beanName);
                        }
                    }
                }
                else {
                    getBean(beanName);
                }
            }
        }

        // Trigger post-initialization callback for all applicable beans...
        for (String beanName : beanNames) {
            Object singletonInstance = getSingleton(beanName);
            if (singletonInstance instanceof SmartInitializingSingleton) {
                SmartInitializingSingleton smartSingleton = (SmartInitializingSingleton) singletonInstance;
                if (System.getSecurityManager() != null) {
                    AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
                        smartSingleton.afterSingletonsInstantiated();
                        return null;
                    }, getAccessControlContext());
                }
                else {
                    smartSingleton.afterSingletonsInstantiated();
                }
            }
        }
    }

 preInstantiateSingletons 的主要作用就是实例化所有剩余的的单例,它会迭代每一个beanNames,根据 beanName 获取 BeanDefinition,如果这个 BeanDefinition 满足三个条件:非抽象、单例、非懒加载,将会进行下一步实例化操作;接下来先判断当前要实例化的bean 是不是 FactoryBean,如果是 FactoryBean,再判断是不是 SmartFactoryBean,如果是 SmartFactoryBean,再调用 SmartFactoryBean#isEagerInit 方法判断是不是非懒加载,如果是非懒加载,调用 AbstractBeanFactory#getBean(java.lang.String) 方法实例化 bean,如果当前bean 不是 FactoryBean, 直接调用 AbstractBeanFactory#getBean(java.lang.String) 方法实例化 。

 

进入 AbstractBeanFactory#getBean(java.lang.String) 方法

    @Override
    public Object getBean(String name) throws BeansException {
        return doGetBean(name, null, null, false);
    }

    @Override
    public <T> T getBean(String name, Class<T> requiredType) throws BeansException {
        return doGetBean(name, requiredType, null, false);
    }

    @Override
    public Object getBean(String name, Object... args) throws BeansException {
        return doGetBean(name, null, args, false);
    }

    /**
     * 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)
     * @return an instance of the bean
     * @throws BeansException if the bean could not be created
     */
    public <T> T getBean(String name, @Nullable Class<T> requiredType, @Nullable Object... args)
            throws BeansException {

        return doGetBean(name, requiredType, args, false);
    }

 我们发现 getBean 有多个重载方法,但这些方法都是空壳方法,真正执行创建并返回bean 的方法是 AbstractBeanFactory#doGetBean 方法

 

 进入 AbstractBeanFactory#doGetBean 方法

    /**
     * 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 {

        //处理 & + beanName 的情况,去掉头部所有的 & 符号
        String beanName = transformedBeanName(name);
        Object bean;

        // 对于手动注册,先检查是否添加到单例缓存池中
        // Eagerly check singleton cache for manually registered singletons.
        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
            bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);
        }

        //检查到单例缓存池中为空时执行下面的语句
        else {
            //如果是原型的 baen 正在创建,抛出异常,refresh() 初始化过程中这一步一定是 false
            // 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) {

                //将当前正在创建的 bean 放到 alreadyCreated 中标记为已创建
                markBeanAsCreated(beanName);
            }

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

                //检查 @DependsOn, 保证 @DependsOn 先初始化
                // Guarantee initialization of beans that the current bean depends on.
                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);
                        }
                    }
                }


                //创建 bean 示例
                // Create bean instance.
                if (mbd.isSingleton()) {
                    //获取单实例bean, 没有就调用 createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
                    //创建一个再返回
                    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();
                    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 {
                                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.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;
    }

 doGetBean 主要是为了创建获取 Bean ,这一部分代码比较长。首先,转换 beanName,如果beanName 是以 “&”,去掉所有开头是 “&” 的字符;第二步,调用 DefaultSingletonBeanRegistry#getSingleton(java.lang.String) 获取单实例bean 赋值给 sharedInstance,如果sharedInstance 不为空且 args 为空,调用 AbstractBeanFactory#getObjectForBeanInstance 方法根据 sharedInstance 实例返回其本身或者 FactoryBean 创建的新的 bean;否则,将当前正在创建的 bean 放到 alreadyCreated 中标记为已创建;然后,检查 @DependsOn, 保证 @DependsOn 先初始化,然后判断BeanDefinition Scope, 如果 scope 是 sington,调用 DefaultSingletonBeanRegistry#getSingleton(String, ObjectFactory<?>) 获取单实例bean 赋值给 sharedInstance,ObjectFactory<?>又调用了 AbstractBeanFactory#createBean 方法创建 bean,调用 AbstractBeanFactory#getObjectForBeanInstance 方法根据 sharedInstance 实例返回其本身或者 FactoryBean 创建的新的 bean;如果 scope 是 prototype,1.将当前 beanName 添加到 prototypesCurrentlyInCreation,2.创建 prototype bean,3.prototypesCurrentlyInCreation 移除当前 beanName,调用 AbstractBeanFactory#getObjectForBeanInstance 方法根据 sharedInstance 实例返回其本身或者 FactoryBean 创建的新的 bean,如果scope为其他类型(如 session, request 等),调用 Scope#get 方法 获取 bean,调用 AbstractBeanFactory#getObjectForBeanInstance 方法根据 sharedInstance 实例返回其本身或者 FactoryBean 创建的新的 bean,最后根据 requiredType 返回执行类型的 bean。

 

进入 DefaultSingletonBeanRegistry#getSingleton(java.lang.String)  方法

public Object getSingleton(String beanName) {
        return getSingleton(beanName, true);
    }

 一个空壳方法,具体调用的是其重载 DefaultSingletonBeanRegistry#getSingleton(java.lang.String, boolean),进入这个方法

    protected Object getSingleton(String beanName, boolean allowEarlyReference) {
        Object singletonObject = this.singletonObjects.get(beanName);
        //如果 singletonObjects 中取到的 singletonObject 不为空且 当前 beanName 正在创建中
        if (singletonObject == null && isSingletonCurrentlyInCreation(beanName)) {
            synchronized (this.singletonObjects) {
                singletonObject = this.earlySingletonObjects.get(beanName);
                //如果 earlySingletonObjects 中取到的 singletonObject 不空且 允许直接引用 earlySingletonObjects 的 bean
                if (singletonObject == null && allowEarlyReference) {
                    // 根据 beanName 从 singletonFactories 获取 singletonFactory
                    ObjectFactory<?> singletonFactory = this.singletonFactories.get(beanName);
                    if (singletonFactory != null) {
                        //调用 singletonFactory 创建 bean ,singletonFactory 应该是调用了 AbstractBeanFactory#createBean 方法创建 bean,
                        //然后将创建的 singletonObject 添加到 earlySingletonObjects,  singletonFactories 中移除 beanName
                        singletonObject = singletonFactory.getObject();
                        this.earlySingletonObjects.put(beanName, singletonObject);
                        this.singletonFactories.remove(beanName);
                    }
                }
            }
        }
        return singletonObject;
    }

 getSington会先从 singletonObjects 获取 bean,如果获取不到且 bean 正在创建中,加锁,从 earlySingletonObjects 中再获取bean,如果再获取不到且 允许直接引用 earlySingletonObjects 中的 bean, 先从 singletonFactories 中获取 singletonFactory,然后调用singletonFactory#get 方法获取bean(从上一步 AbstractBeanFactory#doGetBean 方法我们知道 singletonFactory#get 会调用 AbstractBeanFactory#createBean 方法创建 bean并返回),然后将创建好的 bean 先加入 earlySingletonObjects,再从 singletonFactories 中移除。这一步就是spring 创建bean的三级缓存的具体方法,很重要

 

 接下来再看看 AbstractBeanFactory#getObjectForBeanInstance 方法

    protected Object getObjectForBeanInstance(
            Object beanInstance, String name, String beanName, @Nullable RootBeanDefinition mbd) {

        //如果 name 以 & 开头,代表是 工厂bean, 此时 mbd 设置 isFactoryBean 为true
        // Don‘t let calling code try to dereference the factory if the bean isn‘t a factory.
        if (BeanFactoryUtils.isFactoryDereference(name)) {
            if (beanInstance instanceof NullBean) {
                return beanInstance;
            }
            if (!(beanInstance instanceof FactoryBean)) {
                throw new BeanIsNotAFactoryException(beanName, beanInstance.getClass());
            }
            if (mbd != null) {
                mbd.isFactoryBean = true;
            }
            return beanInstance;
        }

        //如果 beanInstance 不是 FactoryBean, 返回其本身
        // Now we have the bean instance, which may be a normal bean or a FactoryBean.
        // If it‘s a FactoryBean, we use it to create a bean instance, unless the
        // caller actually wants a reference to the factory.
        if (!(beanInstance instanceof FactoryBean)) {
            return beanInstance;
        }

        Object object = null;
        if (mbd != null) {
            mbd.isFactoryBean = true;
        }
        else {
            // 根据 beanName 从 factoryBeanObjectCache 缓存中获取指定的 factoryBean 对象
            object = getCachedObjectForFactoryBean(beanName);
        }
        if (object == null) {
            // Return bean instance from factory.
            FactoryBean<?> factory = (FactoryBean<?>) beanInstance;
            // Caches object obtained from FactoryBean if it is a singleton.
            if (mbd == null && containsBeanDefinition(beanName)) {
                mbd = getMergedLocalBeanDefinition(beanName);
            }
            boolean synthetic = (mbd != null && mbd.isSynthetic());
            // 根据 factoryBean 对象获取真实的 bean 并将 factoryBean 添加到 factoryBeanObjectCache 缓存中
            object = getObjectFromFactoryBean(factory, beanName, !synthetic);
        }
        return object;
    }

 这一步就是判断 bean 实例是不是 FactoryBean, 如果不是,返回本身,如果是,设置其 BeanDefinition 的 isFactoryBean 属性为true,并返回 FactoryBean 创建的 bean 实例

 

 进入 DefaultSingletonBeanRegistry#getSingleton(String, ObjectFactory<?>) 方法

    public Object getSingleton(String beanName, ObjectFactory<?> singletonFactory) {
        Assert.notNull(beanName, "Bean name 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 + "‘");
                }
                //创建实例之前的检查,主要判断实例是否可以添加到并发创建集合中
                beforeSingletonCreation(beanName);
                boolean newSingleton = false;
                boolean recordSuppressedExceptions = (this.suppressedExceptions == null);
                if (recordSuppressedExceptions) {
                    this.suppressedExceptions = new LinkedHashSet<>();
                }
                try {
                    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.
                    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;
                    }
                    afterSingletonCreation(beanName);
                }

                /*
                 * 如果单例对象创建成功,将单例对象添加到缓存中,具体操作有
                 * 1. 将单例对象添加到 singletonObjects
                 * 2. singletonFactories 中移除 objectFactory
                 * 3. earlySingletonObjects 中移除 singletonObject
                 * 4. 将单例对象添加到 registeredSingletons
                 */
                if (newSingleton) {
                    addSingleton(beanName, singletonObject);
                }
            }
            return singletonObject;
        }
    }

  这一步先尝试从 singletonObjects 中获取 bean,如果取到的为空,singletonFactory#get 方法获取 bean并返回(从上一步 AbstractBeanFactory#doGetBean 方法我们知道 singletonFactory#get 会调用 AbstractBeanFactory#createBean 方法创建 bean并返回),再看看 finally 语句块中,如果单实例bean 被创建成功,执行创建成功的后续操作,具体操作为:1. 将单例对象添加到 singletonObjects,2. singletonFactories 中移除 objectFactory,3. earlySingletonObjects 中移除 singletonObject,4. 将单例对象添加到 registeredSingletons

 

 我们发现 doGetBean 方法创建最后都指向 AbstractBeanFactory#createBean 方法,这个方法是个抽象方法,具体的实现为 AbstractAutowireCapableBeanFactory#createBean(String, RootBeanDefinition, Object[]) 进入这个方法

 

spring源码解析-ApplicationContext 启动流程(3)- 执行 AbstractApplicationContext#finishBeanFactoryInitialization(ConfigurableListableBeanFactory) 方法

上一篇:08持久化操作RDB


下一篇:关于android studio 开发flutter多个build.gradle的问题