Spring IOC 初始化刷新流程十一:finishBeanFactoryInitialization(beanFactory)

Spring IOC 初始化刷新流程:https://www.cnblogs.com/jhxxb/p/13609289.html

 

未执行 finishBeanFactoryInitialization() 时的容器

容器内所有的单例 Bean: 有的是前面经历过 getBean() 被提前实例化了,有的是直接 addSingleton() 方法添加的

容器内所有 Bean 的定义信息:自己 @Bean 进去的目前都仅仅存在于 Bean 定义信息内,还并没有真正的实例化

 

方法源码

创建所有非懒加载的单例类(并执行 BeanPostProcessors),我们自定义的 Bean 绝大多数都是在这一步被初始化的,包括依赖注入等

这一步,能让我们更深入的看到 Spring 是如何管理 Bean 的声明周期,以及依赖关系。

public abstract class AbstractApplicationContext extends DefaultResourceLoader implements ConfigurableApplicationContext {
    protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {
        // Initialize conversion service for this context.
        // 初始化上下文的转换服务,ConversionService 是一个类型转换接口
        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.
        // 设置一个内置的值处理器(若没有的话),该处理器作用有点像一个 PropertyPlaceholderConfigurer Bean
        if (!beanFactory.hasEmbeddedValueResolver()) {
            beanFactory.addEmbeddedValueResolver(strVal -> getEnvironment().resolvePlaceholders(strVal));
        }

        // Initialize LoadTimeWeaverAware beans early to allow for registering their transformers early.
        // 注意此处已经调用了 getBean 方法,初始化 LoadTimeWeaverAware Bean
        // getBean() 方法的详细,下面会详细分解
        // LoadTimeWeaverAware 是类加载时织入的意思
        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.
        // 缓存(冻结)所有的 bean definition 数据,不期望以后会改变
        beanFactory.freezeConfiguration();

        // Instantiate all remaining (non-lazy-init) singletons.
        // 这个就是最重要的方法:会把留下来的 Bean,不是 lazy 懒加载的 bean 都实例化掉
        // bean 真正实例化的时刻到了
        beanFactory.preInstantiateSingletons();
    }

public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory implements ConfigurableListableBeanFactory, BeanDefinitionRegistry, Serializable {
    @Override
    public void freezeConfiguration() {
        this.configurationFrozen = true;
        this.frozenBeanDefinitionNames = StringUtils.toStringArray(this.beanDefinitionNames);
    }

preInstantiateSingletons()

public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory implements ConfigurableListableBeanFactory, BeanDefinitionRegistry, Serializable {
    /**
     * 此处绝大部分的单例 Bean 定义信息都会被实例化,但是如果是通过 FactoryBean 定义的,它是懒加载的(如果没人使用,就先不会实例化。只会到使用的时候才实例化)
     * 即实例化的时候只会实例化 FactoryBean,要用的时候才会通过 FactoryBean 创建真正要使用 Bean
     */
    @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.
        // 此处目的,把所有的 bean 定义信息名称,赋值到一个新的集合中
        List<String> beanNames = new ArrayList<>(this.beanDefinitionNames);

        // Trigger initialization of all non-lazy singleton beans...
        for (String beanName : beanNames) {
            RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);
            // 不是抽象类 && 是单例 && 不是懒加载
            if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {
                // 对工厂 Bean 支持:比如第三方框架的继承经常采用这种方式
                if (isFactoryBean(beanName)) {
                    // 拿到工厂 Bean,注意有前缀:FACTORY_BEAN_PREFIX
                    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());
                        }
                        // true:希望马上被初始化
                        if (isEagerInit) {
                            getBean(beanName);
                        }
                    }
                } else {
                    // 普通单例 Bean 初始化,核心逻辑在方法:doGetBean
                    getBean(beanName);
                }
            }
        }

        // Trigger post-initialization callback for all applicable beans...
        // SmartInitializingSingleton#afterSingletonsInstantiated:所有非 lazy 的单例 Bean 实例化完成后的回调方法,Spring4.1 后提供// InitializingBean#afterPropertiesSet:只要自己被创建好了就执行
        // 例如 EventListenerMethodProcessor,它在 afterSingletonsInstantiated 方法里就去处理所有的 Bean 的方法,看哪些被标注了 @EventListener 注解,就提取处理为一个 Listener,通过 addApplicationListener 方法放到容器中
        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 {
                    // 比如:ScheduledAnnotationBeanPostProcessor、CacheAspectSupport、MBeanExporter 等
                    smartSingleton.afterSingletonsInstantiated();
                }
            }
        }
    }

getMergedLocalBeanDefinition()

Bean 定义公共的抽象类是 AbstractBeanDefinition,普通的 Bean 在 Spring 加载 Bean 定义的时候,实例化出来的是 GenericBeanDefinition,而 Spring 上下文包括实例化所有 Bean 用的 AbstractBeanDefinition 是 RootBeanDefinition,这时候就使用getMergedLocalBeanDefinition 方法做了一次转化,将非 RootBeanDefinition 转换为 RootBeanDefinition 以供后续操作。

public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport implements ConfigurableBeanFactory {
    /**
     * 该方法功能说明:在 map 缓存中把 Bean 的定义拿出来。交给 getMergedLocalBeanDefinition 处理。最终转换成 RootBeanDefinition 类型
     * 在转换的过程中,如果 BeanDefinition 的父类不为空,则把父类的属性也合并到 RootBeanDefinition 中,
     * 所以 getMergedLocalBeanDefinition 方法的作用就是获取缓存的 BeanDefinition 对象并合并其父类和本身的属性
     * 注意:如果当前 BeanDefinition 存在父 BeanDefinition,会基于父 BeanDefinition 生成一个 RootBeanDefinition,然后再将调用 OverrideFrom 子 BeanDefinition 的相关属性覆写进去
     */
    protected RootBeanDefinition getMergedLocalBeanDefinition(String beanName) throws BeansException {
        // Quick check on the concurrent map first, with minimal locking.
        RootBeanDefinition mbd = this.mergedBeanDefinitions.get(beanName);
        if (mbd != null && !mbd.stale) {
            return mbd;
        }
        return getMergedBeanDefinition(beanName, getBeanDefinition(beanName));
    }

public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory implements ConfigurableListableBeanFactory, BeanDefinitionRegistry, Serializable {
    @Override
    public BeanDefinition getBeanDefinition(String beanName) throws NoSuchBeanDefinitionException {
        // 把前面已经保存在 IOC 容器里的 BeanDefinition 定义信息返回
        BeanDefinition bd = this.beanDefinitionMap.get(beanName);
        if (bd == null) {
            if (logger.isTraceEnabled()) {
                logger.trace("No bean named '" + beanName + "' found in " + this);
            }
            throw new NoSuchBeanDefinitionException(beanName);
        }
        return bd;
    }

至此,finishBeanFactoryInitialization 这一步完成,所有的单例 Bean 已经创建完成并放置容器里。下面是创建 Bean 的详细流程。

 

主要方法 getBean()

顶层接口为 BeanFactory

/**
 * getBean() 不仅仅是 get,如果 get 不到还可能去实例化一个 Bean 的(默认根据空构造函数进行实例化),因此 args 其实就是为了匹配构造函数而提供的扩展功能
 * 使用前提:
 * 1、传入的参数必须有相对应的构造函数入参与之匹配
 * 2、bean 的 scope 必须设置成 prototype,因为动态传参话 bean 不可以是单例
 */
public interface BeanFactory {

    Object getBean(String name) throws BeansException;

    <T> T getBean(String name, Class<T> requiredType) throws BeansException;

    /**
     * @since 2.5
     */
    Object getBean(String name, Object... args) throws BeansException;

    /**
     * @since 3.0
     */
    <T> T getBean(Class<T> requiredType) throws BeansException;

    /**
     * @since 4.1
     */
    <T> T getBean(Class<T> requiredType, Object... args) throws BeansException;

抽象实现为 AbstractBeanFactory,复写了其中 3 个方法,此处的 doGetBean(),就是 Bean 实例化的核心逻辑

public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport implements ConfigurableBeanFactory {

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

DefaultListableBeanFactory 继承自 AbstractBeanFactory,复写了剩余的 2 个方法

public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory implements ConfigurableListableBeanFactory, BeanDefinitionRegistry, Serializable {
    @Override
    public <T> T getBean(Class<T> requiredType) throws BeansException {
        return getBean(requiredType, (Object[]) null);
    }

    // 上面那个方法是调用这个方法的逻辑
    @Override
    public <T> T getBean(Class<T> requiredType, @Nullable Object... args) throws BeansException {
        Assert.notNull(requiredType, "Required type must not be null");
        Object resolved = resolveBean(ResolvableType.forRawClass(requiredType), args, false);
        if (resolved == null) {
            throw new NoSuchBeanDefinitionException(requiredType);
        }
        return (T) resolved;
    }

    @Nullable
    private <T> T resolveBean(ResolvableType requiredType, @Nullable Object[] args, boolean nonUniqueAsNull) {
        // resolveNamedBean 根据 requiredType 去找。若不止一个会抛错:NoUniqueBeanDefinitionException
        NamedBeanHolder<T> namedBean = resolveNamedBean(requiredType, args, nonUniqueAsNull);
        if (namedBean != null) {
            return namedBean.getBeanInstance();
        }

        // 如果子容器里没有找到 Bean,还会去父容器(若存在的话)里找找看
        BeanFactory parent = getParentBeanFactory();
        if (parent instanceof DefaultListableBeanFactory) {
            return ((DefaultListableBeanFactory) parent).resolveBean(requiredType, args, nonUniqueAsNull);
        } else if (parent != null) {
            ObjectProvider<T> parentProvider = parent.getBeanProvider(requiredType);
            if (args != null) {
                return parentProvider.getObject(args);
            } else {
                return (nonUniqueAsNull ? parentProvider.getIfUnique() : parentProvider.getIfAvailable());
            }
        }
        return null;
    }

 

getBean() 调用的 doGetBean()

public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport implements ConfigurableBeanFactory {
    /**
     * 依赖注入主要有两个过程,一个是实例化 Bean,另一个是将依赖关系注入到 Bean 中
     * 从命名上可以看出:有 do 这个动作的。因此不是简单的 get 有就返回,没有就返回 null 这么简单的操作。而是里面做了实例化、依赖注入、属性赋值、解决循环依赖等一些列操作
     */
    protected <T> T doGetBean(String name, @Nullable Class<T> requiredType, @Nullable Object[] args, boolean typeCheckOnly) throws BeansException {
        // 该方法作用:
        // 1、如果是 FactoryBean,会去掉 Bean 开头的 & 符号
        // 2、能存在传入别名且别名存在多重映射的情况,这里会返回最终的名字,如存在多层别名映射 A->B->C->D,传入 D,最终会返回 A
        String beanName = transformedBeanName(name);
        Object bean;

        // Eagerly check singleton cache for manually registered singletons.
        // getSingleton() 方法的实现,在父类 DefaultSingletonBeanRegistry 中,请先移步下面,看详解
        // 这里先尝试从缓存中获取,若获取不到,就走下面的创建
        // 特别注意的是:这里面走创建(发现是个new的),就加入进缓存里面了 if (newSingleton) {addSingleton(beanName, singletonObject);}   缓存的字段为全局的Map:singletonObjects
        Object sharedInstance = getSingleton(beanName);
        if (sharedInstance != null && args == null) {
            if (logger.isTraceEnabled()) {
                // 这里虽然只是一句日志,但是能说明用意。
                // 若条件为 true,表示这个 Bean 虽然在缓存里,但是并没有完全被初始化(循环引用)
                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 + "'");
                }
            }

            // 在 getBean 方法中,getObjectForBeanInstance 是个频繁使用的方法。因此为了更好的知道细节,下面会详解这个方法
            // 其实简单理解就是处理 FactoryBean 的 getObject() 方法
            bean = 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.
            // 这一步也是必须要做的,若存在父容器,得看看父容器是否实例化过它。避免被重复实例化(若父容器被实例化,就以父容器的为准)
            // 这就是为何,我们扫描 controller,哪怕不加排除什么的,也不会出问题的原因,因为 Spring 中的单例 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 if (requiredType != null) {
                    // No args -> delegate to standard getBean method.
                    return parentBeanFactory.getBean(nameToLookup, requiredType);
                } else {
                    return (T) parentBeanFactory.getBean(nameToLookup);
                }
            }

            // alreadyCreated 中增加此值。表示此 Bean 已经创建,或正在创建
            if (!typeCheckOnly) {
                // 如果创建 bean 不是为了类型检查,则要标记当前 bean 已经被创建,或者即将被创建,以便于 BeanFactory 可以优化重复创建的 bean 的缓存
                markBeanAsCreated(beanName);
            }

            try {
                // 根据名字获取合并过的对应的 RootBeanDefinition
                RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
                // 检查 mbd 是否为抽象的或为单例,但存在 args 的情况(args 只有初始化原型对象才允许存在)
                checkMergedBeanDefinition(mbd, beanName, args);

                // Guarantee initialization of beans that the current bean depends on.
                // 这里很重要,因为 Bean 实例化会有属性注入等,所以这里就是要保证它依赖的那些属性先初始化
                // 这部分是处理循环依赖的核心,@DependsOn 注解可以控制 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 销毁时先销毁依赖的 bean
                        registerDependentBean(dep, beanName);
                        try {
                            // 先创建依赖的 bean
                            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()) { // 单例模式
                    // 尝试从缓存中加载单例 Bean,获取失败就通过 ObjectFactory 的 createBean 方法创建
                    // 这个 getSingleton 方法和上面是重载方法,它支持通过 ObjectFactory 去根据 Scope 来创建对象,具体源码解析见下面
                    sharedInstance = getSingleton(beanName, () -> {
                        try {
                            // 这是创建 Bean 的核心方法,非常重要
                            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.
                            // 执行失败,就销毁 Bean。然后执行对应的 destroy 方法等
                            destroySingleton(beanName);
                            throw ex;
                        }
                    });
                    // 同样的工厂类型 Bean 的处理
                    bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
                } else if (mbd.isPrototype()) { // 原型模式
                    // It's a prototype -> create a new instance.
                    Object prototypeInstance = null;
                    try {
                        beforePrototypeCreation(beanName); // 原型 Bean 创建的前置处理,记录当前 Bean 处于正在创建的状态
                        prototypeInstance = createBean(beanName, mbd, args); // 原型模式创建 Bean
                    } finally {
                        afterPrototypeCreation(beanName); // 原型 Bean 创建后置处理,移除正在创建状态,即当前 Bean 已创建完成
                    }
                    // 同样的工厂类型 Bean 的处理
                    bean = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);
                } else { // 其它 scope 类型的处理
                    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); // 使用原型 Bean 的前置处理
                            try {
                                return createBean(beanName, mbd, args); // 其它 Scope 模式创建 Bean
                            } finally {
                                afterPrototypeCreation(beanName); // 使用原型 Bean 的后置处理
                            }
                        });
                        // 同样的工厂类型 Bean 的处理
                        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.
        // 这里就比较简单了,就是 requiredType,比如要求是 Integer,获得的是 String,那么就会调用转换器转换过来,绝大多数情况下,没什么用
        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;
    }

DefaultSingletonBeanRegistry#getSingleton()

public class DefaultSingletonBeanRegistry extends SimpleAliasRegistry implements SingletonBeanRegistry {
    @Override
    @Nullable
    public Object getSingleton(String beanName) {
        // 尝试从缓存中获取,true 为允许提前依赖
        return getSingleton(beanName, true);
    }

    @Nullable
    protected Object getSingleton(String beanName, boolean allowEarlyReference) {
        // Quick check for existing instance without full singleton lock
        // 此处是先从已经缓存好了的 singletonObjects 的 Map 中,查看有木有(至于当前已经有哪些了,开头有个截图)
        Object singletonObject = this.singletonObjects.get(beanName);

        // 若缓存里没有。并且这个 Bean 必须在创建中,才会进来。
        // singletonsCurrentlyInCreation 字段含义:会缓存下来所有的正在创建中的 Bean,如果有 Bean 是循环引用的,会把这种 Bean 先放进去,这里才会有值
        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<?> singletonFactory = this.singletonFactories.get(beanName);
                            if (singletonFactory != null) {
                                // 如果工厂不为空,则调用工厂方法加载 Bean
                                singletonObject = singletonFactory.getObject();
                                // 记录到提前加载的 Bean 的缓存中
                                this.earlySingletonObjects.put(beanName, singletonObject);
                                // 已经调用工厂加载 Bean,将工厂从缓存中移除,无需再次加载
                                this.singletonFactories.remove(beanName);
                            }
                        }
                    }
                }
            }
        }
        return singletonObject;
    }

DefaultSingletonBeanRegistry#getSingleton(根据 ObjectFactory 结合 Scope 来创建合适的对象)

public class DefaultSingletonBeanRegistry extends SimpleAliasRegistry implements SingletonBeanRegistry {
    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) {
                // 如果这个 Bean 正在被销毁,就抛异常
                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 + "'");
                }
                // 单例 Bean 创建的前置检查:
                // 1、是否在 inCreationCheckExclusions 校验名单里
                // 2、singletonsCurrentlyInCreation 把它添加进去,证明这个 Bean 正在创建中
                beforeSingletonCreation(beanName);
                // 此处先打标记为 false
                boolean newSingleton = false;
                boolean recordSuppressedExceptions = (this.suppressedExceptions == null);
                if (recordSuppressedExceptions) {
                    this.suppressedExceptions = new LinkedHashSet<>();
                }
                try {
                    // 把这个实例生成出来,并且标志位设为 true
                    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) {
                    // 处理异常
                    // 比如我们经常遇到的 UnsatisfiedDependencyException 异常:@Autowired 的时候找不到依赖的 Bean 就是这个异常(一般由 NoSuchBeanDefinitionException 这个异常导致)
                    // 这里会把异常链接拼接起来,然后一起打印出来,非常方便查找问题
                    if (recordSuppressedExceptions) {
                        for (Exception suppressedException : this.suppressedExceptions) {
                            ex.addRelatedCause(suppressedException);
                        }
                    }
                    throw ex;
                } finally {
                    if (recordSuppressedExceptions) {
                        this.suppressedExceptions = null;
                    }
                    // 创建完成后再检查一遍。做的操作为:从正在创建缓存中移除
                    afterSingletonCreation(beanName);
                }

                // 这里非常重要:若是新的 Bean,那就执行 addSingleton 这个方法,为下面 4 步操作:
                // this.singletonObjects.put(beanName, singletonObject); // 缓存起来
                // this.singletonFactories.remove(beanName); // 把对应 ObjectFactory 的缓存移除
                // this.earlySingletonObjects.remove(beanName);
                // this.registeredSingletons.add(beanName);
                if (newSingleton) {
                    addSingleton(beanName, singletonObject);
                }
            }
            return singletonObject;
        }
    }

getObjectForBeanInstance

在 doGetBean 中不论是什么方式获得的 Bean,都会执行 getObjectForBeanInstance 方法。原因是,不论哪种方式获得的 Bean 都是原始的状态,并不是我们真正想要的 Bean。

public class DefaultSingletonBeanRegistry extends SimpleAliasRegistry implements SingletonBeanRegistry {
    /**
     * Cache of singleton objects: bean name to bean instance. 一级 Cache:单例对象
     */
    private final Map<String, Object> singletonObjects = new ConcurrentHashMap<>(256);

    /**
     * Cache of singleton factories: bean name to ObjectFactory. 三级 Cache:单例对象的工厂
     */
    private final Map<String, ObjectFactory<?>> singletonFactories = new HashMap<>(16);

    /**
     * Cache of early singleton objects: bean name to bean instance. 二级 Cache:提前曝光的单例对象
     * 与一级 Cache:singletonFactories 区别在于 earlySingletonObjects 中存放的 bean 不一定是完整的,这个 Map 也是【循环依赖】的关键
     */
    private final Map<String, Object> earlySingletonObjects = new ConcurrentHashMap<>(16);

public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory implements AutowireCapableBeanFactory {
    @Override
    protected Object getObjectForBeanInstance(Object beanInstance, String name, String beanName, @Nullable RootBeanDefinition mbd) {
        String currentlyCreatedBean = this.currentlyCreatedBean.get();
        if (currentlyCreatedBean != null) {
            // 如果 Bean 正在被创建,就注册这个 Bean 所依赖的 Bean,这样当这个 Bean 被销毁时,同时销毁这些依赖的 Bean
            registerDependentBean(beanName, currentlyCreatedBean);
        }
        return super.getObjectForBeanInstance(beanInstance, name, beanName, mbd);
    }

public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport implements ConfigurableBeanFactory {
    protected Object getObjectForBeanInstance(Object beanInstance, String name, String beanName, @Nullable RootBeanDefinition mbd) {
        // Don't let calling code try to dereference the factory if the bean isn't a factory.
        if (BeanFactoryUtils.isFactoryDereference(name)) { // 如果 name 是工厂类的引用名称(name 以 "&" 开头)
            if (beanInstance instanceof NullBean) { // 如果是 NullBean 则直接返回
                return beanInstance;
            }
            if (!(beanInstance instanceof FactoryBean)) { // 如果 beanInstance 不是 FactoryBean 则抛出异常
                throw new BeanIsNotAFactoryException(beanName, beanInstance.getClass());
            }
            if (mbd != null) {
                mbd.isFactoryBean = true;
            }
            return beanInstance;
        }

        // 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.
        // 走到这里,说明现在已经有一个 Bean 实例,该实例可能是一个正常的 Bean 又或者是一个 FactoryBean
        // 如果 beanInstance 不是 Factory,则直接返回
        if (!(beanInstance instanceof FactoryBean)) {
            return beanInstance;
        }

        Object object = null;
        if (mbd != null) {
            mbd.isFactoryBean = true;
        } else { // 若 BeanDefinition 为 null,则从缓存中加载 Bean 对象
            object = getCachedObjectForFactoryBean(beanName);
        }
        // 如果 Object 为 null,则可以确认 beanInstance 一定是 FactoryBean。从而使用 FactoryBean 获取 Bean 对象
        // 通过 beanInstance instanceof FactoryBean 这里判断,如果 beanInstance 不是 FactoryBean 已经直接返回了
        if (object == null) {
            // Return bean instance from factory.
            FactoryBean<?> factory = (FactoryBean<?>) beanInstance;
            // Caches object obtained from FactoryBean if it is a singleton.
            // 检测 beanDefinitionMap 中,也就是所有已加载的类中是否定义了 beanName
            if (mbd == null && containsBeanDefinition(beanName)) {
                // 将存储 XML 配置文件的 GenericBeanDefinition 转换为 RootBeanDefinition
                // 如果指定 beanName 是子类 Bean 的话,会同时合并父类的相关属性
                mbd = getMergedLocalBeanDefinition(beanName);
            }
            // 是否是用户定义的,而不是程序本身定义的
            boolean synthetic = (mbd != null && mbd.isSynthetic());
            // 核心函数,使用 FactoryBean 获得 Bean 对象
            object = getObjectFromFactoryBean(factory, beanName, !synthetic);
        }
        return object;
    }

public abstract class FactoryBeanRegistrySupport extends org.springframework.beans.factory.support.DefaultSingletonBeanRegistry {
    protected Object getObjectFromFactoryBean(FactoryBean<?> factory, String beanName, boolean shouldPostProcess) {
        if (factory.isSingleton() && containsSingleton(beanName)) { // 单例,且缓存中存在该 Bean 实例
            synchronized (getSingletonMutex()) {
                // 从缓存中获取指定的 FactoryBean
                Object object = this.factoryBeanObjectCache.get(beanName);
                if (object == null) {
                    // 为 null,则从 FactoryBean 中获取 Bean
                    object = doGetObjectFromFactoryBean(factory, beanName);
                    // Only post-process and store if not put there already during getObject() call above (e.g. because of circular reference processing triggered by custom getBean calls)
                    // 再次从缓存中获取 Bean 对象,主要是因为自定义的 bean 调用处理循环依赖时可能已经放入缓存
                    Object alreadyThere = this.factoryBeanObjectCache.get(beanName);
                    if (alreadyThere != null) {
                        object = alreadyThere; // 获取缓存中的
                    } else {
                        if (shouldPostProcess) { // 需要后续处理
                            if (isSingletonCurrentlyInCreation(beanName)) { // 如果该 Bean 处于创建中,则返回非未处理的对象(尚未存储该对象)
                                // Temporarily return non-post-processed object, not storing it yet..
                                return object;
                            }
                            // 单例 Bean 创建的前置处理。用于添加标志,表示当前 Bean 正处于创建中
                            beforeSingletonCreation(beanName);
                            try {
                                // 对 FactoryBean 获取的对象进行后置处理,也就是 BeanPostProcessor 的调用
                                object = postProcessObjectFromFactoryBean(object, beanName);
                            } catch (Throwable ex) {
                                throw new BeanCreationException(beanName, "Post-processing of FactoryBean's singleton object failed", ex);
                            } finally {
                                // 单例 Bean 创建的后置处理。用于移除标志,表示当前 Bean 不处于创建中
                                afterSingletonCreation(beanName);
                            }
                        }
                        // 添加到 factoryBeanObjectCache 中进行缓存
                        if (containsSingleton(beanName)) {
                            this.factoryBeanObjectCache.put(beanName, object);
                        }
                    }
                }
                return object;
            }
        } else { // 非单例,或者缓存中不存在
            Object object = doGetObjectFromFactoryBean(factory, beanName); // 从 FactoryBean 中获取对象
            if (shouldPostProcess) { // 需要后续处理
                try {
                    // 对 FactoryBean 获取的对象进行后处理,也就是 BeanPostProcessor 的调用
                    object = postProcessObjectFromFactoryBean(object, beanName);
                } catch (Throwable ex) {
                    throw new BeanCreationException(beanName, "Post-processing of FactoryBean's object failed", ex);
                }
            }
            return object;
        }
    }

    private Object doGetObjectFromFactoryBean(FactoryBean<?> factory, String beanName) throws BeanCreationException {
        Object object;
        try {
            if (System.getSecurityManager() != null) {
                AccessControlContext acc = getAccessControlContext();
                try {
                    object = AccessController.doPrivileged((PrivilegedExceptionAction<Object>) factory::getObject, acc);
                } catch (PrivilegedActionException pae) {
                    throw pae.getException();
                }
            } else {
                // 调用 getObject 方法获取 Bean
                object = factory.getObject();
            }
        } catch (FactoryBeanNotInitializedException ex) {
            throw new BeanCurrentlyInCreationException(beanName, ex.toString());
        } catch (Throwable ex) {
            throw new BeanCreationException(beanName, "FactoryBean threw exception on object creation", ex);
        }

        // Do not accept a null value for a FactoryBean that's not fully initialized yet: Many FactoryBeans just return null then.
        if (object == null) {
            if (isSingletonCurrentlyInCreation(beanName)) {
                throw new BeanCurrentlyInCreationException(beanName, "FactoryBean which is currently in creation returned null from getObject");
            }
            object = new NullBean();
        }
        return object;
    }

 

doGetBean() 中创建 Bean 逻辑调用的是 AbstractAutowireCapableBeanFactory#createBean()

public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory implements AutowireCapableBeanFactory {
    @Override
    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.
        // 确保对应 BeanClass 完成解析(已经加载进来了 Class 对象)具体表现是进行了 ClassLoder.loadClass 或 Class.forName 完成了类加载
        // 主要根据传入的 typesToMatch 生成特定 的ClassLoader,之后还要调用 RootBeanDefinition#resolveBeanClass,根据特定的加载器或者默认加载器加载出 class 属性对应的 Class 对象
        // 判断需要创建的 Bean 是否可以实例化,这个类是否可以通过类装载器来载入(也就说它甚至可能来源于网络)
        Class<?> resolvedClass = resolveBeanClass(mbd, beanName);
        if (resolvedClass != null && !mbd.hasBeanClass() && mbd.getBeanClassName() != null) {
            mbdToUse = new RootBeanDefinition(mbd);
            mbdToUse.setBeanClass(resolvedClass);
        }

        // Prepare method overrides.
        try {
            // 这里主要是解析 <lookup-method name="getFruit" bean="bananer"/> 类似这种方式的依赖注入(Spring 支持 lookup-method,replace-method 两个依赖注入的方式)
            // 它相当于调用指定类里面的指定方法进行注入,所以需要考虑到方法重载的情况,因此这个方法解析的就是这种情况
            // 项目中一般这么使用,非常的不大众,具体原理此处省略
            mbdToUse.prepareMethodOverrides();
        } catch (BeanDefinitionValidationException ex) {
            throw new BeanDefinitionStoreException(mbdToUse.getResourceDescription(), beanName, "Validation of method overrides failed", ex);
        }

        try {
            // Give BeanPostProcessors a chance to return a proxy instead of the target bean instance.
            // 从 doc 解释:给 BeanPostProcessors 一个机会来返回一个代理对象代替目标对象,什么动态代理之类的,都在这里实现的
            // 1、判断当前 Spring 容器是否注册了实现了 InstantiationAwareBeanPostProcessor 接口的后置处理器,如果有,则依次调用其中的 applyBeanPostProcessorsBeforeInstantiation 方法,中间任意一个方法返回不为 null,直接结束调用
            // 2、依次调用所有的 BeanPostProcessor#postProcessAfterInitialization 方法(如果任意一次返回不为 null,终止调用)
            // 这个方法也非常的重要
            // 容器里所有的 InstantiationAwareBeanPostProcessors 实例,都会在此处生效,进行前置处理
            // 下面有解释:BeanPostProcessor 和 InstantiationAwareBeanPostProcessor 的区别,可以分清楚它们执行的时机
            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 {
            // 这里是重点:doCreateBean 创建 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);
        }
    }

    @Nullable
    protected Object resolveBeforeInstantiation(String beanName, RootBeanDefinition mbd) {
        Object bean = null;
        // beforeInstantiationResolved 这个属性如果是 false,表示不需要被前置处理了
        // 然后,唯一能改变它的值的地方,是下面这仅仅一行代码而已,它的访问权限为 package
        if (!Boolean.FALSE.equals(mbd.beforeInstantiationResolved)) {
            // Make sure bean class is actually resolved at this point.
            // 这里 hasInstantiationAwareBeanPostProcessors() 方法就是看属性 hasInstantiationAwareBeanPostProcessors 的值。就是标记容器里是否有 InstantiationAwareBeanPostProcessor 的实现
            // 显然,在执行 addBeanPostProcessor,发现这个 Bean 是这个子类型的时候,就会设为 true 了。同理的还有 hasDestructionAwareBeanPostProcessors 这个属性,表示销毁的处理器
            if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
                // 拿到最终的目标类型(放置被别的包装过)
                // 可能依赖于 AbstractBeanFactory#resolveBeanClass 这个方法去解析
                Class<?> targetType = determineTargetType(beanName, mbd);
                if (targetType != null) {
                    // 先执行执行 InstantiationAwareBeanPostProcessor#postProcessBeforeInstantiation 回调方法
                    // 里面的逻辑也比较简单:拿到缓存好的(List)所有 BeanPostProcessors,如果是 InstantiationAwareBeanPostProcessor 就执行
                    // 只要有一个 result 不为 null,后面的所有后置处理器的方法就不执行了,直接返回(所以执行顺序很重要)
                    // 1、ConfigurationClassPostProcessor$ImportAwareBeanPostProcessor 这个内部类就是这个类型。主要是增强、完善处理 @Configuration 这种类,但它并没有重写 postProcessBeforeInstantiation 方法,所以默认是返回 null
                    // 2、CommonAnnotationBeanPostProcessor/Autowired...也没做处理(若你自己不去注册,那系统里就再没有了)
                    // 需要注意的是,如果我们采用了 AOP、声明式事务等,这里就会有了
                    bean = applyBeanPostProcessorsBeforeInstantiation(targetType, beanName);
                    // 如果 Bean 不为 null,那就直接返回了,不执行后面的 After 了
                    if (bean != null) {
                        // 注意,这里是 Initialization,是初始化的后置方法,是 BeanPostProcessor 的方法,也就是说初始化完成后的方法。
                        // 为何这里执行这个方法呢?是因为我们上面说了,如果返回不为 null,后面都都会被短路掉。但是此处 Spring 还是让我们执行了初始化后的处理器方法,这点需要引起注意
                        // 就是说:即使 Bean 在实例化前已经返回了一个不为 null 的对象,别的方法都被短路了,但是我的【初始化】后置处理器方法 applyBeanPostProcessorsAfterInitializationh 还是可以执行的
                        // 这里面可以关注一下这个类:ApplicationListenerDetector
                        // 初始化之后的方法返回了 null,那就需要调用 doCreateBean 生成对象了
                        bean = applyBeanPostProcessorsAfterInitialization(bean, beanName);
                    }
                }
            }
            mbd.beforeInstantiationResolved = (bean != null);
        }
        return bean;
    }

这一步中的几个接口

public interface BeanPostProcessor {
    /**
     * Bean 初始化前,一般是在调用 init-method 前,实例化早于初始化
     * 初始化:在目标对象被实例化之后,并且属性也被设置之后调用
     */
    @Nullable
    default Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        return bean;
    }

    /**
     * Bean 初始化后
     */
    @Nullable
    default Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        return bean;
    }
}

public interface InstantiationAwareBeanPostProcessor extends BeanPostProcessor {
    /**
     * Bean 实例化前
     * 实例化:一个创建 Bean 的过程,即调用 Bean 的构造函数及 Bean 的属性设置,单例 Bean 放入单例池中
     * 返回值类型为 Object,由于这个时候目标对象还未实例化,所以可以返回其它实例(比如代理对象)。
     * 如果该方法的返回值代替原本该生成的目标对象,后续就只有 postProcessAfterInitialization 方法会调用,其它方法不再调用。否则按照正常的流程走
     */
    @Nullable
    default Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) throws BeansException {
        return null;
    }

    /**
     * Bean 实例化后
     * 这个时候对象已经被实例化,但是该实例的属性还未被设置,都是 null。因为它的返回值是决定要不要调用 postProcessPropertyValues 方法的其中一个因素(因为还有一个因素是 mbd.getDependencyCheck())
     * 如果该方法返回 false,并且不需要 check,那么 postProcessPropertyValues 就会被忽略不执行。如果返回 true,postProcessPropertyValues 就会被执行
     */
    default boolean postProcessAfterInstantiation(Object bean, String beanName) throws BeansException {
        return true;
    }

    @Nullable
    default PropertyValues postProcessProperties(PropertyValues pvs, Object bean, String beanName) throws BeansException {
        return null;
    }

    /**
     * 已经过时,由上面的 postProcessProperties 代替
     * 对属性值进行修改(这个时候属性值还未被设置,但是我们可以修改原本该设置进去的属性值)。如果 postProcessAfterInstantiation 方法返回 false,该方法可能不会被调用
     */
    @Deprecated
    @Nullable
    default PropertyValues postProcessPropertyValues(PropertyValues pvs, PropertyDescriptor[] pds, Object bean, String beanName) throws BeansException {
        return pvs;
    }
}

public interface SmartInstantiationAwareBeanPostProcessor extends InstantiationAwareBeanPostProcessor {
    /**
     * 预测 Bean 的类型,返回第一个预测成功的 Class 类型,如果不能预测则返回 null
     */
    @Nullable
    default Class<?> predictBeanType(Class<?> beanClass, String beanName) throws BeansException {
        return null;
    }

    /**
     * 若目标对象有多个构造器,在这里可以进行一些定制化,选择合适的构造器
     * beanClass 参数表示目标实例的类型,beanName 是目标实例在 Spring 容器中的 name
     * 返回值是个构造器数组,如果返回 null,会执行下一个 PostProcessor 的 determineCandidateConstructors 方法;否则选取该 PostProcessor 选择的构造器
     * Spring4.0 之后可以泛型依赖注入:
     * @Autowired private BaseRepository<Student> studentRepo;
     * @Autowired private BaseRepository<Faculty> facultyRepo;
     */
    @Nullable
    default Constructor<?>[] determineCandidateConstructors(Class<?> beanClass, String beanName) throws BeansException {
        return null;
    }

    /**
     * 获得提前暴露的 Bean 引用。主要用于解决循环引用的问题
     * 只有单例对象才会调用此方法,在处理循环引用的时候,这个方法会起到比较关键的作用
     */
    default Object getEarlyBeanReference(Object bean, String beanName) throws BeansException {
        return bean;
    }
}

public interface MergedBeanDefinitionPostProcessor extends BeanPostProcessor {
    /**
     * 给后续回调中缓存一些 meta 信息
     */
    void postProcessMergedBeanDefinition(RootBeanDefinition beanDefinition, Class<?> beanType, String beanName);

    default void resetBeanDefinition(String beanName) {
    }
}

 

createBean() 调用的 doCreateBean()

public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory implements AutowireCapableBeanFactory {
    protected Object doCreateBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) throws BeanCreationException {
        // Instantiate the bean.
        BeanWrapper instanceWrapper = null; // 用 BeanWrapper 来持有创建出来的 Bean 对象
        if (mbd.isSingleton()) { // 如果是单例的话,先把缓存中的同名 Bean 清除
            instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
        }
        // 实际创建的交给 createBeanInstance 来完成,Bean 的生成,这里会使用默认的类生成器,包装成 BeanWrapperImpl 类,为了下面的 populateBean 方法的属性注入做准备
        if (instanceWrapper == null) {
            instanceWrapper = createBeanInstance(beanName, mbd, args);
        }
        Object bean = instanceWrapper.getWrappedInstance();
        Class<?> beanType = instanceWrapper.getWrappedClass();
        // 如果不是 NullBean,则将 resolvedTargetType 属性设置为当前的 WrappedClass
        if (beanType != NullBean.class) {
            mbd.resolvedTargetType = beanType;
        }

        // Allow post-processors to modify the merged bean definition.
        synchronized (mbd.postProcessingLock) {
            if (!mbd.postProcessed) {
                try {
                    // 此处处理 MergedBeanDefinitionPostProcessor 接口的处理器,它在 BeanPostProcessor 的基础上增加了 postProcessMergedBeanDefinition 方法,在此处就被调用了
                    // 主要是处理 @PostConstruct、@Autowire、@Value、@Resource、@PreDestory 等这些注解
                    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.
        // 如果当前 Bean 是单例,且支持循环依赖,且当前 Bean 正在创建,通过往 singletonFactories 添加一个 objectFactory,这样后期如果有其它 Bean 依赖该 Bean,可以从 singletonFactories 获取到 Bean
        // getEarlyBeanReference 可以对返回的 Bean 进行修改,这边目前除了可能会返回动态代理对象 其它的都是直接返回 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");
            }
            // 这里面主要是解决循环引用问题,借助了这个工厂
            // 主要是调用处理器:SmartInstantiationAwareBeanPostProcessor#getEarlyBeanReference 方法去找到前期的 Bean(若存在这种处理器的话)
            addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
        }

        // Initialize the bean instance.
        Object exposedObject = bean; // 这个 Obj,就是最终要返回的对象
        try {
            // 非常重要的一步:给已经初始化的属性们赋值,对 Bean 进行填充,在这里面完成依赖注入的相关内容
            populateBean(beanName, mbd, instanceWrapper);
            // 完成属性依赖注入后,进一步初始化 Bean,具体进行了以下操作:
            // 若实现了 BeanNameAware、BeanClassLoaderAware、BeanFactoryAwareAware 等接口,则注入相关对象
            // 遍历后置处理器,调用实现的 postProcessBeforeInitialization 方法
            // 如果实现了 initialzingBean,调用实现的 afterPropertiesSet()
            // 如果配置了 init-mothod,调用相应的 init 方法
            // 遍历后置处理器,调用实现的 postProcessAfterInitialization 方法
            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);
            }
        }

        // 如果 earlySingletonExposure 为 true,尝试从缓存获取该 Bean(一般存放在 singletonFactories 对象,通过调用 getObject 把对象存入 earlySingletonObjects),
        // 分别从 singletonObjects 和 earlySingletonObjects 获取对象,这里依然是处理循环依赖相关问题的
        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 'getBeanNamesForType' with the 'allowEagerInit' flag turned off, for example.");
                    }
                }
            }
        }

        // Register bean as disposable.
        try {
            // 如果有需要,就注册 DisposableBean,这样 Bean 销毁的时候,这种后置处理器也会生效了
            registerDisposableBeanIfNecessary(beanName, bean, mbd);
        } catch (BeanDefinitionValidationException ex) {
            throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex);
        }

        return exposedObject;
    }

    protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) {
        // Make sure bean class is actually resolved at this point.
        // 确保 Bean 类已经解析过了,可以实例化
        Class<?> beanClass = resolveBeanClass(mbd, beanName);
        // 确保 class 不为空,并且访问权限为 public,所以注意如果你的 Class 不是 public 的,Spring 给你创建不了对象
        if (beanClass != null && !Modifier.isPublic(beanClass.getModifiers()) && !mbd.isNonPublicAccessAllowed()) {
            throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Bean class isn't public, and non-public access not allowed: " + beanClass.getName());
        }

        // 配置的一种特殊的 callback 回调方法,通过这个 callback 创建 Bean
        // Supplier 返回的 Obj,最终会交给 obtainFromSupplier 包装成 BeanWrapper
        Supplier<?> instanceSupplier = mbd.getInstanceSupplier();
        if (instanceSupplier != null) {
            return obtainFromSupplier(instanceSupplier, beanName);
        }

        // 这是 Spring 支持的又一种方式:使用工厂方法来进行 Bean 的实例化
        if (mbd.getFactoryMethodName() != null) {
            return instantiateUsingFactoryMethod(beanName, mbd, args);
        }

        // Shortcut when re-creating the same bean...
        // 一个类可能有多个构造器,所以 Spring 得根据参数个数、类型确定需要调用的构造器
        // 在使用构造器创建实例后,Spring 会将解析过后确定下来的构造器或工厂方法保存在缓存中,避免再次创建相同 Bean 时再次解析
        boolean resolved = false;
        boolean autowireNecessary = false;
        if (args == null) {
            synchronized (mbd.constructorArgumentLock) {
                if (mbd.resolvedConstructorOrFactoryMethod != null) {
                    // 标记一下,已经解析过 class 的构造器
                    resolved = true;
                    autowireNecessary = mbd.constructorArgumentsResolved;
                }
            }
        }
        if (resolved) { // resolved 若为 true,表示已经解析过构造器了,就下面直接使用解析好的构造器实例化 Bean
            if (autowireNecessary) {
                return autowireConstructor(beanName, mbd, null, null);
            } else {
                return instantiateBean(beanName, mbd);
            }
        }

        // Candidate constructors for autowiring?
        // 通过此方法,去检测可用的构造器:这里使用 SmartInstantiationAwareBeanPostProcessor,它通过循环调用处理器的 determineCandidateConstructors 方法,谁第一个发现一个可用的构造器,就 return,否则返回 null
        // 这里需要注意:如果 Bean 没有空的构造函数(比如只有一个参数的构造函数,那么 Spring 会用这个构造函数实例化 Bean,并且入参会自动从容器里去找出来)
        Constructor<?>[] ctors = determineConstructorsFromBeanPostProcessors(beanClass, beanName);
        // ctors 不为 null,或者标注了处理机制是构造器注入方式,AbstractBeanDefinition#setAutowireMode 可以设置模式
        if (ctors != null || mbd.getResolvedAutowireMode() == AUTOWIRE_CONSTRUCTOR || mbd.hasConstructorArgumentValues() || !ObjectUtils.isEmpty(args)) {
            // 构造器选择策略,自动注入
            return autowireConstructor(beanName, mbd, ctors, args);
        }

        // Preferred constructors for default construction?
        ctors = mbd.getPreferredConstructors();
        if (ctors != null) {
            return autowireConstructor(beanName, mbd, ctors, null);
        }

        // No special handling: simply use no-arg constructor. 使用无参构造器初始化
        return instantiateBean(beanName, mbd);
    }

determineConstructorsFromBeanPostProcessors()

public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory implements AutowireCapableBeanFactory {
    @Nullable
    protected Constructor<?>[] determineConstructorsFromBeanPostProcessors(@Nullable Class<?> beanClass, String beanName) throws BeansException {
        if (beanClass != null && hasInstantiationAwareBeanPostProcessors()) {
            for (BeanPostProcessor bp : getBeanPostProcessors()) {
                if (bp instanceof SmartInstantiationAwareBeanPostProcessor) {
                    SmartInstantiationAwareBeanPostProcessor ibp = (SmartInstantiationAwareBeanPostProcessor) bp;
                    Constructor<?>[] ctors = ibp.determineCandidateConstructors(beanClass, beanName);
                    if (ctors != null) {
                        return ctors;
                    }
                }
            }
        }
        return null;
    }

public class AutowiredAnnotationBeanPostProcessor extends InstantiationAwareBeanPostProcessorAdapter implements MergedBeanDefinitionPostProcessor, PriorityOrdered, BeanFactoryAware {
    @Override
    @Nullable
    public Constructor<?>[] determineCandidateConstructors(Class<?> beanClass, final String beanName) throws BeanCreationException {
        // Let's check for lookup methods here...
        // 检测 @Lookup 注解,这个注解的注入方式,已经不推荐使用了
        if (!this.lookupMethodsChecked.contains(beanName)) {
            if (AnnotationUtils.isCandidateClass(beanClass, Lookup.class)) {
                try {
                    Class<?> targetClass = beanClass;
                    do {
                        ReflectionUtils.doWithLocalMethods(targetClass, method -> {
                            Lookup lookup = method.getAnnotation(Lookup.class);
                            if (lookup != null) {
                                Assert.state(this.beanFactory != null, "No BeanFactory available");
                                LookupOverride override = new LookupOverride(method, lookup.value());
                                try {
                                    RootBeanDefinition mbd = (RootBeanDefinition) this.beanFactory.getMergedBeanDefinition(beanName);
                                    mbd.getMethodOverrides().addOverride(override);
                                } catch (NoSuchBeanDefinitionException ex) {
                                    throw new BeanCreationException(beanName, "Cannot apply @Lookup to beans without corresponding bean definition");
                                }
                            }
                        });
                        targetClass = targetClass.getSuperclass();
                    } while (targetClass != null && targetClass != Object.class);
                } catch (IllegalStateException ex) {
                    throw new BeanCreationException(beanName, "Lookup method resolution failed", ex);
                }
            }
            this.lookupMethodsChecked.add(beanName);
        }

        // Quick check on the concurrent map first, with minimal locking.
        // 先从缓存里去看,有没有解析过此类的构造函数,对每个类的构造函数只解析一次,解析完会存储结果,以备下次复用
        Constructor<?>[] candidateConstructors = this.candidateConstructorsCache.get(beanClass);
        if (candidateConstructors == null) {
            // Fully synchronized resolution now...
            synchronized (this.candidateConstructorsCache) {
                // 为了线程安全,这里继续校验一次
                candidateConstructors = this.candidateConstructorsCache.get(beanClass);
                if (candidateConstructors == null) {
                    Constructor<?>[] rawCandidates;
                    try {
                        // 拿到此 Class 所有的构造函数(一般的类都只有一个空的构造函数),当然也可以写多个
                        rawCandidates = beanClass.getDeclaredConstructors();
                    } catch (Throwable ex) {
                        throw new BeanCreationException(beanName, "Resolution of declared constructors on bean Class [" + beanClass.getName() +
                                "] from ClassLoader [" + beanClass.getClassLoader() + "] failed", ex);
                    }
                    List<Constructor<?>> candidates = new ArrayList<>(rawCandidates.length);
                    Constructor<?> requiredConstructor = null;
                    Constructor<?> defaultConstructor = null;
                    // 兼容 Kotlin 类型做的处理
                    Constructor<?> primaryConstructor = BeanUtils.findPrimaryConstructor(beanClass);
                    int nonSyntheticConstructors = 0;
                    for (Constructor<?> candidate : rawCandidates) { // 遍历处理构造器
                        if (!candidate.isSynthetic()) {
                            nonSyntheticConstructors++;
                        } else if (primaryConstructor != null) {
                            continue;
                        }
                        // 找到构造器里有 @Aotowaired 或者 @Value 注解的直接信息
                        MergedAnnotation<?> ann = findAutowiredAnnotation(candidate);
                        if (ann == null) {
                            // 此方法的目是拿到目标类:比如若是被 cglib 代理过的,那就拿到父类(因为 cglib 是通过子类的形式加强的)
                            Class<?> userClass = ClassUtils.getUserClass(beanClass);
                            if (userClass != beanClass) { // 确实是被 CGLIB 代理过的,那就再解析一次,看看父类是否有 @Autowaired 这种构造器
                                try {
                                    Constructor<?> superCtor = userClass.getDeclaredConstructor(candidate.getParameterTypes());
                                    ann = findAutowiredAnnotation(superCtor);
                                } catch (NoSuchMethodException ex) {
                                    // Simply proceed, no equivalent superclass constructor found...
                                }
                            }
                        }
                        if (ann != null) { // 存在注解标注的这种构造器
                            // 这个判断很有必要,表示要求的构造器最多只能有一个
                            // 注:@Autowired 标注的构造器数量最多只能有一个(当然,required=true 的只能有一个,=false 的可以有多个)
                            if (requiredConstructor != null) {
                                throw new BeanCreationException(beanName, "Invalid autowire-marked constructor: " + candidate +
                                        ". Found constructor with 'required' Autowired annotation already: " + requiredConstructor);
                            }
                            // 获取 Autowire 注解中 required 属性值
                            boolean required = determineRequiredStatus(ann);
                            if (required) { // 只有是 true 才往下走(默认值为 true)
                                if (!candidates.isEmpty()) {
                                    throw new BeanCreationException(beanName, "Invalid autowire-marked constructors: " + candidates +
                                            ". Found constructor with 'required' Autowired annotation: " + candidate);
                                }
                                // 这样子,这个构造器就是必须的了,记录下来
                                requiredConstructor = candidate;
                            }
                            // 把标注有 @Autowired 注解的构造器,记录下来,作为候选的构造器
                            candidates.add(candidate);
                        } else if (candidate.getParameterCount() == 0) {
                            // 这个就重要了,若该构造器没有被标注 @Autowired 注解,但是它是无参构造器,那就当选的构造器(当然是以标注了 @Autowired 的为准)
                            // 注意:虽然把默认的构造函数记录下来了,但是并没有加进 candidates 里
                            defaultConstructor = candidate;
                        }
                    }
                    if (!candidates.isEmpty()) { // 若能找到候选的构造器
                        // Add default constructor to list of optional constructors, as fallback.
                        if (requiredConstructor == null) {
                            if (defaultConstructor != null) {
                                candidates.add(defaultConstructor);
                            } else if (candidates.size() == 1 && logger.isInfoEnabled()) { // 如果没有默认的无参构造函数,且有 @Autowired(required = false)的构造函数,则发出警告
                                logger.info("Inconsistent constructor declaration on bean with name '" + beanName + "': single autowire-marked constructor flagged as optional - " +
                                        "this constructor is effectively required since there is no " + "default constructor to fall back to: " + candidates.get(0));
                            }
                        }
                        candidateConstructors = candidates.toArray(new Constructor<?>[0]);
                    } else if (rawCandidates.length == 1 && rawCandidates[0].getParameterCount() > 0) {
                        // 有且仅有一个构造器,并且该构造器的参数大于 0 个,那就是我们要找的构造器了,这种情况,也是平时我们使用得比较多的情况
                        candidateConstructors = new Constructor<?>[]{rawCandidates[0]};
                    } else if (nonSyntheticConstructors == 2 && primaryConstructor != null && defaultConstructor != null && !primaryConstructor.equals(defaultConstructor)) {
                        // 处理 primaryConstructor 以及 nonSyntheticConstructors,兼容 Kotlin 一般都达不到
                        candidateConstructors = new Constructor<?>[]{primaryConstructor, defaultConstructor};
                    } else if (nonSyntheticConstructors == 1 && primaryConstructor != null) {
                        candidateConstructors = new Constructor<?>[]{primaryConstructor};
                    } else { // 啥构造器都没找到,那就是空数组
                        candidateConstructors = new Constructor<?>[0];
                    }
                    this.candidateConstructorsCache.put(beanClass, candidateConstructors);
                }
            }
        }
        // 若有多个构造函数,但是没有一个标记了 @Autowired,此处不会报错,但是返回 null,交给后面的策略处理
        return (candidateConstructors.length > 0 ? candidateConstructors : null);
    }
}

autowireConstructor()

public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory implements AutowireCapableBeanFactory {
    protected BeanWrapper autowireConstructor(String beanName, RootBeanDefinition mbd, @Nullable Constructor<?>[] ctors, @Nullable Object[] explicitArgs) {
        // 此处的 this,就是 DefaultListableBeanFactory
        return new ConstructorResolver(this).autowireConstructor(beanName, mbd, ctors, explicitArgs);
    }

class ConstructorResolver {
    public BeanWrapper autowireConstructor(String beanName, RootBeanDefinition mbd, @Nullable Constructor<?>[] chosenCtors, @Nullable Object[] explicitArgs) {
        // 先实例化一个 BeanWrapperImpl 类对象
        BeanWrapperImpl bw = new BeanWrapperImpl();
        // initBeanWrapper 做了一些事,比如注册解析器、value 解析器等
        this.beanFactory.initBeanWrapper(bw);

        Constructor<?> constructorToUse = null;
        ArgumentsHolder argsHolderToUse = null;
        Object[] argsToUse = null;

        if (explicitArgs != null) { // 如果构造参数不为空,就直接使用这些参数
            argsToUse = explicitArgs;
        } else { // 否则构造函数的入参,交给 Spring 处理。它会去容器里拿
            Object[] argsToResolve = null;
            synchronized (mbd.constructorArgumentLock) {
                // 获取已缓存解析的构造函数或工厂方法(resolvedConstructorOrFactoryMethod 用于缓存已解析的构造函数或工厂方法)
                // 如果缓存不为空,并且构造参数已经解析缓存了,(constructorArgumentsResolved 为包可见,用于表示构造参数状态是否已经解析)
                // 显然首次进来,都是为 null,并且没有被解析
                constructorToUse = (Constructor<?>) mbd.resolvedConstructorOrFactoryMethod;
                if (constructorToUse != null && mbd.constructorArgumentsResolved) {
                    // Found a cached constructor...
                    argsToUse = mbd.resolvedConstructorArguments;
                    if (argsToUse == null) {
                        argsToResolve = mbd.preparedConstructorArguments;
                    }
                }
            }
            if (argsToResolve != null) { // 如果上面没有解析过,显然这里参数就是 null 了,argsToUse 也就还为 null,Spring 下面继续解析
                argsToUse = resolvePreparedArguments(beanName, mbd, bw, constructorToUse, argsToResolve, true);
            }
        }

        if (constructorToUse == null || argsToUse == null) { // 如果缓存的构造器不存在,就说明没有 Bean 进行过解析,需要去关联对应的 Bean 的构造器
            // Take specified constructors, if any.
            // 如果传入的构造器为空,则获取 bean 的 Class 对象,然后根据 bean 是不是 public 修饰的来按照不同的方式获取所有的构造器
            // 显然,我们这里(大都都会有构造器)
            // 但是此处我们发现,即使构造器不是 public 的,这里也能够遭到构造器来进行实例化
            Constructor<?>[] candidates = chosenCtors;
            if (candidates == null) {
                Class<?> beanClass = mbd.getBeanClass();
                try {
                    // getDeclaredConstructors 返回所有的构造器(包括 public 和 private 修饰的),getConstructors 返回 public 修饰的
                    candidates = (mbd.isNonPublicAccessAllowed() ? beanClass.getDeclaredConstructors() : beanClass.getConstructors());
                } catch (Throwable ex) {
                    throw new BeanCreationException(mbd.getResourceDescription(), beanName,
                            "Resolution of declared constructors on bean Class [" + beanClass.getName() + "] from ClassLoader [" + beanClass.getClassLoader() + "] failed", ex);
                }
            }

            if (candidates.length == 1 && explicitArgs == null && !mbd.hasConstructorArgumentValues()) {
                Constructor<?> uniqueCandidate = candidates[0];
                if (uniqueCandidate.getParameterCount() == 0) {
                    synchronized (mbd.constructorArgumentLock) {
                        mbd.resolvedConstructorOrFactoryMethod = uniqueCandidate;
                        mbd.constructorArgumentsResolved = true;
                        mbd.resolvedConstructorArguments = EMPTY_ARGS;
                    }
                    bw.setBeanInstance(instantiate(beanName, mbd, uniqueCandidate, EMPTY_ARGS));
                    return bw;
                }
            }

            // Need to resolve the constructor.
            // 我们的传值 chosenCtors 显然不为 null,所以此值为 true
            boolean autowiring = (chosenCtors != null || mbd.getResolvedAutowireMode() == AutowireCapableBeanFactory.AUTOWIRE_CONSTRUCTOR);
            ConstructorArgumentValues resolvedValues = null;

            int minNrOfArgs;
            if (explicitArgs != null) { // 若传入的构造参数不为空,那最小参数长度以它为准
                minNrOfArgs = explicitArgs.length;
            } else {
                // 这里相当于要解析出构造函数的参数了,解析对应的构造参数然后添加到 ConstructorArgumentValues 中
                ConstructorArgumentValues cargs = mbd.getConstructorArgumentValues();
                resolvedValues = new ConstructorArgumentValues();
                minNrOfArgs = resolveConstructorArguments(beanName, mbd, bw, cargs, resolvedValues);
            }

            // 构造器排序,按照访问方式和数量对构造器进行排序;public > protect > private,在同为 public 时构造器入参多的排在前面
            // 所以排在第一位的,是 public 的,参数最多的构造器
            AutowireUtils.sortConstructors(candidates);
            int minTypeDiffWeight = Integer.MAX_VALUE;
            // 记录下,引起歧义的构造器们。就是记录下来,如果存在这种歧义,抛异常的时候用来告诉调用者
            Set<Constructor<?>> ambiguousConstructors = null;
            LinkedList<UnsatisfiedDependencyException> causes = null;
            // 开始遍历排序后的构造器了
            for (Constructor<?> candidate : candidates) {
                // 拿到构造器参数的类型们
                int parameterCount = candidate.getParameterCount();

                // constructorToUse 不为 null(表示已经找到了合适构造器),但是呢,连参数个数的长度都对应不上,那就直接 break,后面的构造器全都不用看了
                if (constructorToUse != null && argsToUse != null && argsToUse.length > parameterCount) {
                    // Already found greedy constructor that can be satisfied -> do not look any further, there are only less greedy constructors left.
                    break;
                }
                // 如果参数个数比最小个数还小,那就继续下一个构造器吧。
                if (parameterCount < minNrOfArgs) {
                    continue;
                }

                ArgumentsHolder argsHolder;
                Class<?>[] paramTypes = candidate.getParameterTypes();
                if (resolvedValues != null) {
                    try {
                        // 兼容 JDK6 提供的 @ConstructorProperties 这个注解,如果它标注了参数名,那就以它的名字为准
                        // @ConstructorProperties 的作用:构造函数上的注解,显示该构造函数的参数如何与构造对象的 getter 方法相对应
                        String[] paramNames = ConstructorPropertiesChecker.evaluate(candidate, parameterCount);
                        if (paramNames == null) { // 否则,就自己解析
                            // 一般都是 Bean 工厂默认的 DefaultParameterNameDiscoverer 解析出变量名
                            ParameterNameDiscoverer pnd = this.beanFactory.getParameterNameDiscoverer();
                            if (pnd != null) {
                                paramNames = pnd.getParameterNames(candidate);
                            }
                        }
                        // 根据获取到的参数名和已经查到的构造参数和构造参数类型来创建用户创建构造器用的构造参数数组
                        // 这个数组中包含了原始的参数列表和构造后的参数列表,用来对比用
                        argsHolder = createArgumentArray(beanName, mbd, resolvedValues, bw, paramTypes, paramNames, getUserDeclaredConstructor(candidate), autowiring, candidates.length == 1);
                    } catch (UnsatisfiedDependencyException ex) {
                        if (logger.isTraceEnabled()) {
                            logger.trace("Ignoring constructor [" + candidate + "] of bean '" + beanName + "': " + ex);
                        }
                        // Swallow and try next constructor.
                        if (causes == null) {
                            causes = new LinkedList<>();
                        }
                        causes.add(ex);
                        continue;
                    }
                } else {
                    // Explicit arguments given -> arguments length must match exactly.
                    if (parameterCount != explicitArgs.length) {
                        continue;
                    }
                    argsHolder = new org.springframework.beans.factory.support.ConstructorResolver.ArgumentsHolder(explicitArgs);
                }

                // lenientConstructorResolution 的值 ture 与 false 区别:
                // 默认 true,在大部分情况下都是使用[宽松模式],即使多个构造函数的参数数量相同、类型存在父子类、接口实现类关系也能正常创建 Bean
                // false 表示严格模式。与上面相反
                // typeDiffWeight:返回不同的个数的权重
                int typeDiffWeight = (mbd.isLenientConstructorResolution() ? argsHolder.getTypeDifferenceWeight(paramTypes) : argsHolder.getAssignabilityWeight(paramTypes));
                // Choose this constructor if it represents the closest match.
                if (typeDiffWeight < minTypeDiffWeight) { // 根据权重,选择一个最为合适的构造器
                    // 大都进这里来,然后是没有 ambiguousConstructors 的
                    constructorToUse = candidate;
                    argsHolderToUse = argsHolder;
                    argsToUse = argsHolder.arguments;
                    minTypeDiffWeight = typeDiffWeight;
                    ambiguousConstructors = null;
                } else if (constructorToUse != null && typeDiffWeight == minTypeDiffWeight) {
                    if (ambiguousConstructors == null) {
                        ambiguousConstructors = new LinkedHashSet<>();
                        ambiguousConstructors.add(constructorToUse);
                    }
                    ambiguousConstructors.add(candidate);
                }
            }

            // 如果此时还没发现可用的构造器,那这里就开始处理异常
            if (constructorToUse == null) {
                if (causes != null) {
                    UnsatisfiedDependencyException ex = causes.removeLast();
                    for (Exception cause : causes) {
                        this.beanFactory.onSuppressedException(cause);
                    }
                    throw ex;
                }
                throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Could not resolve matching constructor " +
                        "(hint: specify index/type/name arguments for simple parameters to avoid type ambiguities)");
            } else if (ambiguousConstructors != null && !mbd.isLenientConstructorResolution()) {
                throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Ambiguous constructor matches found in bean '" + beanName + "' " +
                        "(hint: specify index/type/name arguments for simple parameters to avoid type ambiguities): " + ambiguousConstructors);
            }

            if (explicitArgs == null && argsHolderToUse != null) {
                argsHolderToUse.storeCache(mbd, constructorToUse);
            }
        }

        Assert.state(argsToUse != null, "Unresolved constructor arguments");
        // 下面步骤都是通用的,用上面得到的构造器(无论是从 Bean 对象中获取的还是 Spring 自己构建的)和参数来反射创建 Bean 实例,并放到 BeanWrapperImpl 对象中然后返回
        bw.setBeanInstance(instantiate(beanName, mbd, constructorToUse, argsToUse));
        return bw;
    }

    private Object instantiate(String beanName, RootBeanDefinition mbd, Constructor<?> constructorToUse, Object[] argsToUse) {
        try {
            // 拿到生成 Bean 实例化策略,默认值为 CglibSubclassingInstantiationStrategy 用 CGLIB 生成子类的方式
            InstantiationStrategy strategy = this.beanFactory.getInstantiationStrategy();
            if (System.getSecurityManager() != null) {
                return AccessController.doPrivileged((PrivilegedAction<Object>) () -> strategy.instantiate(mbd, beanName, this.beanFactory, constructorToUse, argsToUse), this.beanFactory.getAccessControlContext());
            } else {
                // 主要就是调用了策略器的 instantiate,对 Bean 进行了最终的实例化
                // 此方法为重载方法,此处因为不需要代理,所以执行的直接是 SimpleInstantiationStrategy#instantiate
                // 到此处,Bean 正式创建,然后继续到 doCreateBean 方法
                return strategy.instantiate(mbd, beanName, this.beanFactory, constructorToUse, argsToUse);
            }
        } catch (Throwable ex) {
            throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Bean instantiation via constructor failed", ex);
        }
    }

 

doCreateBean() 调用了 populateBean() 和 initializeBean()

populateBean 做 Bean 属性赋值操作(依赖注入)

public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory implements AutowireCapableBeanFactory {
    // 在完成 Bean 实例化后,Spring 容器会给这个 Bean 注入相关的依赖 Bean
    protected void populateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw) {
        // 对实例 Bean 的判空校验
        if (bw == null) {
            if (mbd.hasPropertyValues()) {
                throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Cannot apply property values to null instance");
            } else {
                // Skip property population phase for null instance.
                return;
            }
        }

        // Give any InstantiationAwareBeanPostProcessors the opportunity to modify the
        // state of the bean before properties are set. This can be used, for example,
        // to support styles of field injection.
        // 给 InstantiationAwareBeanPostProcessors 最后一次机会,在属性注入前修改 Bean 的属性值
        // 具体通过调用 postProcessAfterInstantiation 方法,如果调用返回 false,表示不必继续进行依赖注入,直接返回
        if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
            for (BeanPostProcessor bp : getBeanPostProcessors()) {
                if (bp instanceof InstantiationAwareBeanPostProcessor) {
                    InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
                    // postProcessAfterInstantiation 这个方法返回 true,后面的处理器才会继续执行,返回 false,后面的就不会再执行了
                    if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {
                        return;
                    }
                }
            }
        }
        // pvs 是一个 MutablePropertyValues 实例,里面实现了 PropertyValues 接口,提供属性的读写操作实现,同时可以通过调用构造函数实现深拷贝
        PropertyValues pvs = (mbd.hasPropertyValues() ? mbd.getPropertyValues() : null);

        int resolvedAutowireMode = mbd.getResolvedAutowireMode();
        // 根据 Bean 配置的依赖注入方式完成注入,默认是 0,即不走以下逻辑,所有的依赖注入都需要在 xml(或者 @Bean 中)文件中有显式的配置
        // 如果设置了相关的依赖装配方式,会遍历 Bean 中的属性,根据类型或名称来完成相应注入,无需额外配置
        if (resolvedAutowireMode == AUTOWIRE_BY_NAME || resolvedAutowireMode == AUTOWIRE_BY_TYPE) {
            // 深拷贝当前已有的配置
            MutablePropertyValues newPvs = new MutablePropertyValues(pvs);
            // Add property values based on autowire by name if applicable.
            if (resolvedAutowireMode == AUTOWIRE_BY_NAME) {
                autowireByName(beanName, mbd, bw, newPvs); // 根据名称进行注入
            }
            // Add property values based on autowire by type if applicable.
            if (resolvedAutowireMode == AUTOWIRE_BY_TYPE) {
                autowireByType(beanName, mbd, bw, newPvs); // 根据类型进行注入
            }
            // 结合注入后的配置,覆盖当前配置
            pvs = newPvs;
        }

        boolean hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors();
        // 是否进行依赖检查,默认值就是 None,所以此处返回 false,表示不需要依赖检查(关于依赖检查的 4 种模式,建议使用 @Required 来显示控制)
        // @Required 注解作用于 Bean setter 方法上,用于检查一个 Bean 的属性的值在配置期间是否被赋予或设置(populated)
        boolean needsDepCheck = (mbd.getDependencyCheck() != AbstractBeanDefinition.DEPENDENCY_CHECK_NONE);

        PropertyDescriptor[] filteredPds = null;
        if (hasInstAwareBpps) {
            if (pvs == null) {
                pvs = mbd.getPropertyValues();
            }
            // 在这调用了 InstantiationAwareBeanPostProcessor#postProcessPropertyValues 方法,若返回 null,整个 populateBean 方法就结束了
            for (BeanPostProcessor bp : getBeanPostProcessors()) {
                if (bp instanceof InstantiationAwareBeanPostProcessor) {
                    InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
                    PropertyValues pvsToUse = ibp.postProcessProperties(pvs, bw.getWrappedInstance(), beanName);
                    if (pvsToUse == null) {
                        if (filteredPds == null) {
                            filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
                        }
                        // 关于 postProcessPropertyValues 的实现,有几个处理器是非常关键的:
                        // 比如 AutowiredAnnotationBeanPostProcessor、CommonAnnotationBeanPostProcessor 等
                        pvsToUse = ibp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName);
                        // 若返回 null,Spring 表示你已经属性值都设置好了,那它也不再管了
                        if (pvsToUse == null) {
                            return;
                        }
                    }
                    pvs = pvsToUse;
                }
            }
        }
        if (needsDepCheck) {
            if (filteredPds == null) {
                // 过滤出所有需要进行依赖检查的属性编辑器
                filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
            }
            checkDependencies(beanName, mbd, filteredPds, pvs);
        }
        // 将 pvs 上所有的属性填充到 BeanWrapper 对应的 Bean 实例中
        // 注意:这一步完成结束后为止。我们的 Bean 依赖的 parent,还只是 RuntimeBeanReference 类型,还并不是真实的 Parent 这个 Bean
        // 在 Spring 的解析段,其它容器中是没有依赖的 Bean 的实例的,因此这个被依赖的 Bean 需要表示成 RuntimeBeanReferenc 对象,并将它放到 BeanDefinition 的 MutablePropertyValues 中。
        if (pvs != null) {
            applyPropertyValues(beanName, mbd, bw, pvs);
        }
    }

    protected void autowireByName(String beanName, AbstractBeanDefinition mbd, BeanWrapper bw, MutablePropertyValues pvs) {
        // 根据 bw 的 PropertyDescriptors,遍历出所有可写的(即 set 方法存在),存在于 BeanDefinition 里的 PropertyValues,且不是简单属性的属性名
        // 简单属性的判定参照下面方法,主要涵盖基本类型及其包装类,Number、Date 等
        String[] propertyNames = unsatisfiedNonSimpleProperties(mbd, bw);
        for (String propertyName : propertyNames) {
            // 再说明一下 containsLocalBean 这个方法,和 containsBean 的区别在于它只在自己的容器里找,不去父容器里找,其余的一样
            if (containsBean(propertyName)) {
                // 注意:此处找到依赖了,调用了 getBean(),所以即使现在仅仅只是 Bean 定义,那么会被创建实例对象
                Object bean = getBean(propertyName);
                pvs.add(propertyName, bean);
                // 注册依赖关系
                // 此处需要知道的是:Spring 中使用 dependentBeanMap 和 dependenciesForBeanMap 来管理这些 Bean 的依赖关系:
                // Map<String, Set<String>> dependentBeanMap:存放当前 Bean 被引用的 Bean 的集合
                // Map<String, Set<String>> dependenciesForBeanMap:存放当前 Bean 所依赖的 Bean 的集合
                // 依赖注入的具体实现是在 BeanWrapperImpl 类中的 setPropertyValue 方法里
                registerDependentBean(propertyName, beanName);
                if (logger.isTraceEnabled()) {
                    logger.trace("Added autowiring by name from bean name '" + beanName + "' via property '" + propertyName + "' to bean named '" + propertyName + "'");
                }
            } else {
                if (logger.isTraceEnabled()) {
                    logger.trace("Not autowiring property '" + propertyName + "' of bean '" + beanName + "' by name: no matching bean found");
                }
            }
        }
    }

    protected void autowireByType(String beanName, AbstractBeanDefinition mbd, BeanWrapper bw, MutablePropertyValues pvs) {
        // 类型转换器,如果没有指定,就用 BeanWrapper 这个转换器
        TypeConverter converter = getCustomTypeConverter();
        if (converter == null) {
            converter = bw;
        }

        Set<String> autowiredBeanNames = new LinkedHashSet<>(4);
        String[] propertyNames = unsatisfiedNonSimpleProperties(mbd, bw);
        for (String propertyName : propertyNames) {
            try {
                PropertyDescriptor pd = bw.getPropertyDescriptor(propertyName);
                // Don't try autowiring by type for type Object: never makes sense,
                // even if it technically is a unsatisfied, non-simple property.
                // 如果是 Object 类型不进行装配
                if (Object.class != pd.getPropertyType()) {
                    // 获取相关的写方法参数
                    MethodParameter methodParam = BeanUtils.getWriteMethodParameter(pd);
                    // Do not allow eager init for type matching in case of a prioritized post-processor.
                    // 看看实例是否实现了 PriorityOrdered 接口,若没有实现,就稍后点加载吧
                    boolean eager = !(bw.getWrappedInstance() instanceof PriorityOrdered);
                    DependencyDescriptor desc = new AutowireByTypeDependencyDescriptor(methodParam, eager);
                    // 这里会根据传入 desc 里的入参类型,作为依赖装配的类型
                    // 再根据这个类型在 BeanFacoty 中查找所有类或其父类相同的 BeanName
                    // 最后根据 BeanName 获取或初始化相应的类,然后将所有满足条件的 BeanName 填充到 autowiredBeanNames 中
                    Object autowiredArgument = resolveDependency(desc, beanName, autowiredBeanNames, converter);
                    if (autowiredArgument != null) {
                        pvs.add(propertyName, autowiredArgument);
                    }
                    // 需要注入的依赖都拿到后,就开始注册这些依赖吧
                    for (String autowiredBeanName : autowiredBeanNames) {
                        // 注册这些依赖
                        registerDependentBean(autowiredBeanName, beanName);
                        if (logger.isTraceEnabled()) {
                            logger.trace("Autowiring by type from bean name '" + beanName + "' via property '" + propertyName + "' to bean named '" + autowiredBeanName + "'");
                        }
                    }
                    autowiredBeanNames.clear();
                }
            } catch (BeansException ex) {
                throw new UnsatisfiedDependencyException(mbd.getResourceDescription(), beanName, propertyName, ex);
            }
        }
    }

populateBean 中调用的一些 InstantiationAwareBeanPostProcessor

// 这里就是解析该 Bean 的 Autowired 信息,然后给 inject 进去
public class AutowiredAnnotationBeanPostProcessor extends InstantiationAwareBeanPostProcessorAdapter implements MergedBeanDefinitionPostProcessor, PriorityOrdered, BeanFactoryAware {
    @Deprecated
    @Override
    public PropertyValues postProcessPropertyValues(PropertyValues pvs, PropertyDescriptor[] pds, Object bean, String beanName) {
        return postProcessProperties(pvs, bean, beanName);
    }

    @Override
    public PropertyValues postProcessProperties(PropertyValues pvs, Object bean, String beanName) {
        InjectionMetadata metadata = findAutowiringMetadata(beanName, bean.getClass(), pvs);
        try {
            metadata.inject(bean, beanName, pvs);
        } catch (BeanCreationException ex) {
            throw ex;
        } catch (Throwable ex) {
            throw new BeanCreationException(beanName, "Injection of autowired dependencies failed", ex);
        }
        return pvs;
    }

//  和 AutowiredAnnotationBeanPostProcessor 一样,它处理 JSR-250 的注解,如 @Resource
public class CommonAnnotationBeanPostProcessor extends InitDestroyAnnotationBeanPostProcessor implements InstantiationAwareBeanPostProcessor, BeanFactoryAware, Serializable {
    @Deprecated
    @Override
    public PropertyValues postProcessPropertyValues(PropertyValues pvs, PropertyDescriptor[] pds, Object bean, String beanName) {
        return postProcessProperties(pvs, bean, beanName);
    }

    @Override
    public PropertyValues postProcessProperties(PropertyValues pvs, Object bean, String beanName) {
        InjectionMetadata metadata = findResourceMetadata(beanName, bean.getClass(), pvs);
        try {
            metadata.inject(bean, beanName, pvs);
        } catch (Throwable ex) {
            throw new BeanCreationException(beanName, "Injection of resource dependencies failed", ex);
        }
        return pvs;
    }

// 它就是去校验,标注了 @Required 注解的,必须是存在这个 Bean 的
// 从 5.1 版开始弃用,建议使用构造函数注入必需的 Bean(或自定义 InitializingBean 的实现)
@Deprecated
public class RequiredAnnotationBeanPostProcessor extends InstantiationAwareBeanPostProcessorAdapter implements MergedBeanDefinitionPostProcessor, PriorityOrdered, BeanFactoryAware {
    @Override
    public PropertyValues postProcessPropertyValues(PropertyValues pvs, PropertyDescriptor[] pds, Object bean, String beanName) {
        if (!this.validatedBeanNames.contains(beanName)) {
            if (!shouldSkip(this.beanFactory, beanName)) {
                List<String> invalidProperties = new ArrayList<>();
                for (PropertyDescriptor pd : pds) {
                    if (isRequiredProperty(pd) && !pvs.contains(pd.getName())) {
                        invalidProperties.add(pd.getName());
                    }
                }
                if (!invalidProperties.isEmpty()) {
                    throw new BeanInitializationException(buildExceptionMessage(invalidProperties, beanName));
                }
            }
            this.validatedBeanNames.add(beanName);
        }
        return pvs;
    }

InjectionMetadata#inject 处理依赖注入,实现为 AutowiredAnnotationBeanPostProcessor 的内部类

public class InjectionMetadata {
    public void inject(Object target, @Nullable String beanName, @Nullable PropertyValues pvs) throws Throwable {
        Collection<InjectedElement> checkedElements = this.checkedElements;
        Collection<InjectedElement> elementsToIterate = (checkedElements != null ? checkedElements : this.injectedElements);
        if (!elementsToIterate.isEmpty()) {
            for (InjectedElement element : elementsToIterate) {
                if (logger.isTraceEnabled()) {
                    logger.trace("Processing injected element of bean '" + beanName + "': " + element);
                }
                // 主要的方法,还是在 InjectedElement#inject 里
                element.inject(target, beanName, pvs);
            }
        }
    }

    public abstract static class InjectedElement {
        protected void inject(Object target, @Nullable String requestingBeanName, @Nullable PropertyValues pvs) throws Throwable {
            if (this.isField) {
                Field field = (Field) this.member;
                ReflectionUtils.makeAccessible(field);
                field.set(target, getResourceToInject(target, requestingBeanName));
            } else {
                if (checkPropertySkipping(pvs)) {
                    return;
                }
                try {
                    Method method = (Method) this.member;
                    ReflectionUtils.makeAccessible(method);
                    method.invoke(target, getResourceToInject(target, requestingBeanName));
                } catch (InvocationTargetException ex) {
                    throw ex.getTargetException();
                }
            }
        }
    }

public class AutowiredAnnotationBeanPostProcessor extends InstantiationAwareBeanPostProcessorAdapter implements MergedBeanDefinitionPostProcessor, PriorityOrdered, BeanFactoryAware {
    private class AutowiredFieldElement extends InjectionMetadata.InjectedElement {
        @Override
        protected void inject(Object bean, @Nullable String beanName, @Nullable PropertyValues pvs) throws Throwable {
            // 拿到这个字段名
            Field field = (Field) this.member;
            Object value;
            // 大多数情况下,这里都是 false
            if (this.cached) {
                value = resolvedCachedArgument(beanName, this.cachedFieldValue);
            } else {
                DependencyDescriptor desc = new DependencyDescriptor(field, this.required);
                desc.setContainingClass(bean.getClass());
                Set<String> autowiredBeanNames = new LinkedHashSet<>(1);
                Assert.state(beanFactory != null, "No BeanFactory available");
                // 转换器,没有手动注册,默认都是 SimpleTypeConverter
                TypeConverter typeConverter = beanFactory.getTypeConverter();
                try {
                    // 把当前 bean 所依赖的这个 Bean 解析出来(从 Spring 容器里面拿,或者别的地方获取)
                    value = beanFactory.resolveDependency(desc, beanName, autowiredBeanNames, typeConverter);
                } catch (BeansException ex) {
                    throw new UnsatisfiedDependencyException(null, beanName, new InjectionPoint(field), ex);
                }
                synchronized (this) {
                    if (!this.cached) {
                        // 如果已经拿到了这个 Bean 实例
                        if (value != null || this.required) {
                            this.cachedFieldValue = desc;
                            // 把该 Bean 的依赖关系再注册一次
                            registerDependentBeans(beanName, autowiredBeanNames);
                            // 因为是按照类型注入,所以肯定只能有一个,否则上面解析就已经报错了
                            if (autowiredBeanNames.size() == 1) {
                                String autowiredBeanName = autowiredBeanNames.iterator().next();
                                // 这里是来处理放置缓存的字段值
                                if (beanFactory.containsBean(autowiredBeanName) && beanFactory.isTypeMatch(autowiredBeanName, field.getType())) {
                                    this.cachedFieldValue = new ShortcutDependencyDescriptor(desc, autowiredBeanName, field.getType());
                                }
                            }
                        } else {
                            this.cachedFieldValue = null;
                        }
                        this.cached = true;
                    }
                }
            }
            // 给该对象的该字段赋值。注意这里 makeAccessible 设置为 true 了,所以即使你的字段是 private 的也可以
            if (value != null) {
                ReflectionUtils.makeAccessible(field);
                field.set(bean, value);
            }
        }

    private class AutowiredMethodElement extends InjectionMetadata.InjectedElement {
        @Override
        protected void inject(Object bean, @Nullable String beanName, @Nullable PropertyValues pvs) throws Throwable {

initializeBean 做 Bean 初始化操作

public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory implements AutowireCapableBeanFactory {
    protected Object initializeBean(String beanName, Object bean, @Nullable RootBeanDefinition mbd) {
        // 先执行所有的 AwareMethods
        if (System.getSecurityManager() != null) {
            AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
                invokeAwareMethods(beanName, bean);
                return null;
            }, getAccessControlContext());
        } else {
            invokeAwareMethods(beanName, bean);
        }

        Object wrappedBean = bean;
        if (mbd == null || !mbd.isSynthetic()) {
            // 执行所有的 BeanPostProcessor#postProcessBeforeInitialization,初始化之前的处理器方法
            // 规则:只要谁反回了 null,后面的就都不要执行了
            // 这里面实现 postProcessBeforeInitialization 的处理器就很多了,有很多对 Aware 进行了扩展的
            wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
        }

        try {
            // 这里就开始执行 afterPropertiesSet(实现了 InitializingBean 接口)方法和 initMethod
            // 备注:这里 initMethod 方法的名称不能是 afterPropertiesSet,并且这个类不是 InitializingBean 类型才会调用,需要特别注意。
            // (然后该方法只有方法名,所以肯定是反射调用,效率稍微低那么一丢丢)
            // 由此可以见,实现这个接口的初始化方法,是在标注形如 @PostConstruct 之后执行的
            invokeInitMethods(beanName, wrappedBean, mbd);
        } catch (Throwable ex) {
            throw new BeanCreationException((mbd != null ? mbd.getResourceDescription() : null), beanName, "Invocation of init method failed", ex);
        }
        if (mbd == null || !mbd.isSynthetic()) {
            // 整个 Bean 都初始化完成了,就执行后置处理器的这个方法
            // 如果谁反回了 null,后面的处理器都不会再执行了
            wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
        }

        return wrappedBean;
    }

    // 相关 Aware 接口为:BeanNameAware、BeanClassLoaderAware、BeanFactoryAware
    // 这些都是 spring 将数据暴露出去的一种方式,我们直接实现这个接口就能拿到了
    private void invokeAwareMethods(String beanName, Object bean) {
        if (bean instanceof Aware) {
            if (bean instanceof BeanNameAware) {
                ((BeanNameAware) bean).setBeanName(beanName);
            }
            if (bean instanceof BeanClassLoaderAware) {
                ClassLoader bcl = getBeanClassLoader();
                if (bcl != null) {
                    ((BeanClassLoaderAware) bean).setBeanClassLoader(bcl);
                }
            }
            if (bean instanceof BeanFactoryAware) {
                ((BeanFactoryAware) bean).setBeanFactory(AbstractAutowireCapableBeanFactory.this);
            }
        }
    }

initializeBean 中 applyBeanPostProcessorsBeforeInitialization 方法调用的一些 BeanPostProcessor

class ApplicationContextAwareProcessor implements BeanPostProcessor {
    @Override
    @Nullable
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        if (!(bean instanceof EnvironmentAware || bean instanceof EmbeddedValueResolverAware ||
                bean instanceof ResourceLoaderAware || bean instanceof ApplicationEventPublisherAware ||
                bean instanceof MessageSourceAware || bean instanceof ApplicationContextAware)) {
            return bean;
        }

        AccessControlContext acc = null;

        if (System.getSecurityManager() != null) {
            acc = this.applicationContext.getBeanFactory().getAccessControlContext();
        }

        if (acc != null) {
            AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
                invokeAwareInterfaces(bean);
                return null;
            }, acc);
        } else {
            invokeAwareInterfaces(bean);
        }

        return bean;
    }

    private void invokeAwareInterfaces(Object bean) {
        if (bean instanceof EnvironmentAware) {
            ((EnvironmentAware) bean).setEnvironment(this.applicationContext.getEnvironment());
        }
        if (bean instanceof EmbeddedValueResolverAware) {
            ((EmbeddedValueResolverAware) bean).setEmbeddedValueResolver(this.embeddedValueResolver);
        }
        if (bean instanceof ResourceLoaderAware) {
            ((ResourceLoaderAware) bean).setResourceLoader(this.applicationContext);
        }
        if (bean instanceof ApplicationEventPublisherAware) {
            ((ApplicationEventPublisherAware) bean).setApplicationEventPublisher(this.applicationContext);
        }
        if (bean instanceof MessageSourceAware) {
            ((MessageSourceAware) bean).setMessageSource(this.applicationContext);
        }
        if (bean instanceof ApplicationContextAware) {
            ((ApplicationContextAware) bean).setApplicationContext(this.applicationContext);
        }
    }

// 对 bean 进行数据校验
public class BeanValidationPostProcessor implements BeanPostProcessor, InitializingBean {
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        if (!this.afterInitialization) {
            doValidate(bean);
        }
        return bean;
    }

class BootstrapContextAwareProcessor implements BeanPostProcessor {
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        if (this.bootstrapContext != null && bean instanceof BootstrapContextAware) {
            ((BootstrapContextAware) bean).setBootstrapContext(this.bootstrapContext);
        }
        return bean;
    }

public class ServletContextAwareProcessor implements BeanPostProcessor {
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        if (getServletContext() != null && bean instanceof ServletContextAware) {
            ((ServletContextAware) bean).setServletContext(getServletContext());
        }
        if (getServletConfig() != null && bean instanceof ServletConfigAware) {
            ((ServletConfigAware) bean).setServletConfig(getServletConfig());
        }
        return bean;
    }

public class LoadTimeWeaverAwareProcessor implements BeanPostProcessor, BeanFactoryAware {
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        if (bean instanceof LoadTimeWeaverAware) {
            LoadTimeWeaver ltw = this.loadTimeWeaver;
            if (ltw == null) {
                Assert.state(this.beanFactory != null, "BeanFactory required if no LoadTimeWeaver explicitly specified");
                ltw = this.beanFactory.getBean(ConfigurableApplicationContext.LOAD_TIME_WEAVER_BEAN_NAME, LoadTimeWeaver.class);
            }
            ((LoadTimeWeaverAware) bean).setLoadTimeWeaver(ltw);
        }
        return bean;
    }

// 处理声明周期注解方法的处理器。有了它,就允许用 @PostConstruct 和 @PreDestroy 注解去代替 InitializingBean 和 DisposableBean 接口
public class InitDestroyAnnotationBeanPostProcessor implements DestructionAwareBeanPostProcessor, MergedBeanDefinitionPostProcessor, PriorityOrdered, Serializable {
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        LifecycleMetadata metadata = findLifecycleMetadata(bean.getClass());
        try {
            metadata.invokeInitMethods(bean, beanName);
        }
        catch (InvocationTargetException ex) {
            throw new BeanCreationException(beanName, "Invocation of init method failed", ex.getTargetException());
        }
        catch (Throwable ex) {
            throw new BeanCreationException(beanName, "Failed to invoke init method", ex);
        }
        return bean;
    }

initializeBean 中 applyBeanPostProcessorsAfterInitialization 方法调用的一些 BeanPostProcessor

// 把所有的 ApplicationListener 的 Bean,都加入到 addApplicationListener,放到广播器里面
class ApplicationListenerDetector implements DestructionAwareBeanPostProcessor, MergedBeanDefinitionPostProcessor {
    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) {
        if (bean instanceof ApplicationListener) {
            // potentially not detected as a listener by getBeanNamesForType retrieval
            Boolean flag = this.singletonNames.get(beanName);
            if (Boolean.TRUE.equals(flag)) {
                // singleton bean (top-level or inner): register on the fly
                this.applicationContext.addApplicationListener((ApplicationListener<?>) bean);
            } else if (Boolean.FALSE.equals(flag)) {
                if (logger.isWarnEnabled() && !this.applicationContext.containsBean(beanName)) {
                    // inner bean with other scope - can't reliably process events
                    logger.warn("Inner bean '" + beanName + "' implements ApplicationListener interface " +
                            "but is not reachable for event multicasting by its containing ApplicationContext " +
                            "because it does not have singleton scope. Only top-level listener beans are allowed " +
                            "to be of non-singleton scope.");
                }
                this.singletonNames.remove(beanName);
            }
        }
        return bean;
    }

// 校验
public class BeanValidationPostProcessor implements BeanPostProcessor, InitializingBean {
    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        if (this.afterInitialization) {
            doValidate(bean);
        }
        return bean;
    }

// 解析方法中标注有 @Scheduled 注解的,然后加入当作一个任务进行执行
public class ScheduledAnnotationBeanPostProcessor implements ScheduledTaskHolder, MergedBeanDefinitionPostProcessor, DestructionAwareBeanPostProcessor,
        Ordered, EmbeddedValueResolverAware, BeanNameAware, BeanFactoryAware, ApplicationContextAware, SmartInitializingSingleton, ApplicationListener<ContextRefreshedEvent>, DisposableBean {
    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) {
        if (bean instanceof AopInfrastructureBean || bean instanceof TaskScheduler || bean instanceof ScheduledExecutorService) {
            // Ignore AOP infrastructure such as scoped proxies.
            return bean;
        }

        Class<?> targetClass = AopProxyUtils.ultimateTargetClass(bean);
        if (!this.nonAnnotatedClasses.contains(targetClass) && AnnotationUtils.isCandidateClass(targetClass, Arrays.asList(Scheduled.class, Schedules.class))) {
            Map<Method, Set<Scheduled>> annotatedMethods = MethodIntrospector.selectMethods(targetClass, (MethodIntrospector.MetadataLookup<Set<Scheduled>>) method -> {
                Set<Scheduled> scheduledMethods = AnnotatedElementUtils.getMergedRepeatableAnnotations(method, Scheduled.class, Schedules.class);
                return (!scheduledMethods.isEmpty() ? scheduledMethods : null);
            });
            if (annotatedMethods.isEmpty()) {
                this.nonAnnotatedClasses.add(targetClass);
                if (logger.isTraceEnabled()) {
                    logger.trace("No @Scheduled annotations found on bean class: " + targetClass);
                }
            } else {
                // Non-empty set of methods
                annotatedMethods.forEach((method, scheduledMethods) -> scheduledMethods.forEach(scheduled -> processScheduled(scheduled, method, bean)));
                if (logger.isTraceEnabled()) {
                    logger.trace(annotatedMethods.size() + " @Scheduled methods processed on bean '" + beanName + "': " + annotatedMethods);
                }
            }
        }
        return bean;
    }

// 当 Servlet 是以 Bean 的形式注入容器的时候,Bean 初始化完成后,会自动调用它的 init 方法
// 如果 config 为 null,那么它传入可能为代理的 DelegatingServletConfig
public class SimpleServletPostProcessor implements DestructionAwareBeanPostProcessor, ServletContextAware, ServletConfigAware {
    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        if (bean instanceof Servlet) {
            ServletConfig config = this.servletConfig;
            if (config == null || !this.useSharedServletConfig) {
                config = new DelegatingServletConfig(beanName, this.servletContext);
            }
            try {
                ((Servlet) bean).init(config);
            } catch (ServletException ex) {
                throw new BeanInitializationException("Servlet.init threw exception", ex);
            }
        }
        return bean;
    }

整个 initializeBean 流程

  1. 调用各类 Aware 接口
  2. 执行 applyBeanPostProcessorsBeforeInitialization 初始化前的处置操作
  3. 调用 InitializingBean 接口初始化 (如果配置了 method-init,则调用其方法初始化 )
  4. 调用 applyBeanPostProcessorsAfterInitialization 初始化之后的处置操作

 

执行 finishBeanFactoryInitialization() 后的容器

 

Note:Spring 中方法调用层级,对于某个功能中涉及到许多辅助类的逻辑(缓存、前后置处理等)时,可以把这些辅助类逻辑放到功能方法中,把真正的功能逻辑抽取到 doXxx() 方法里。

protected Object getObjectFromFactoryBean(FactoryBean<?> factory, String beanName, boolean shouldPostProcess) {
    // 省略其它无关代码...
    object = doGetObjectFromFactoryBean(factory, beanName);
}

 


https://blog.csdn.net/f641385712/article/details/88410362

https://blog.csdn.net/f641385712/article/details/88205840

https://blog.csdn.net/f641385712/article/details/88376022

posted @ 2020-12-07 15:05  江湖小小白  阅读(701)  评论(1编辑  收藏  举报