Spring源码学习笔记(十二)、finishBeanFactoryInitialization

得意时要看淡,失意时要看开。不论得意失意,切莫大意;不论成功失败,切莫止步。志得意满时,需要的是淡然,给自己留一条退路;失意落魄时,需要的是泰然,给自己觅一条出路Spring源码学习笔记(十二)、finishBeanFactoryInitialization,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com,来源:原文

一、方法功能概述

// 初始化所有的singleton beans(lazy-init的除外)
finishBeanFactoryInitialization(beanFactory);

初始化所有的singleton beans(lazy-init的除外)

二、整体代码展示

/**
 * Finish the initialization of this context's bean factory,
 * 完成此上下文的bean工厂的初始化,
 * initializing all remaining singleton beans.
 * 初始化所有剩余的单例bean。
 */
protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {
    // 初始化名字为conversionService的Bean
    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));
    }

    // 尝试为beanFactory增加EmbeddedValueResolver,比如PropertyPlaceholderConfigurer
    if (!beanFactory.hasEmbeddedValueResolver()) {
        beanFactory.addEmbeddedValueResolver(strVal -> getEnvironment().resolvePlaceholders(strVal));
    }

    // 获取并初始化LoadTimeWeaverAware
    String[] weaverAwareNames = beanFactory.getBeanNamesForType(LoadTimeWeaverAware.class, false, false);
    for (String weaverAwareName : weaverAwareNames) {
        getBean(weaverAwareName);
    }

    // 禁用临时ClassLoader
    beanFactory.setTempClassLoader(null);

    // 禁止再对已注册的beanDefinition做修改,因为接下来要开始创建bean了
    beanFactory.freezeConfiguration();

    // 实例化所有剩余的(非懒加载)的单例。(重点!!!)
    beanFactory.preInstantiateSingletons();
}

三、详细代码解读、preInstantiateSingletons(重点!!!)

实例化所有剩余的(非懒加载)的单例

先看下调用流程图(假设A对象依赖B对象,B对象依赖A对象)

Spring源码学习笔记(十二)、finishBeanFactoryInitialization

1、我们重点看下preInstantiateSingletons方法,进入到类DefaultListableBeanFactory中的preInstantiateSingletons方法

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

    // 获取所有已注册的beanDefinition名字
    List<String> beanNames = new ArrayList<>(this.beanDefinitionNames);

    // 循环每个beanDefinition名字,做初始化操作
    for (String beanName : beanNames) {
        // 合并父类的配置
        RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);
        // 非抽象、非懒加载的单例是需要初始化的,其他情况不需要初始化
        if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {
            //如果是FactoryBean
            if (isFactoryBean(beanName)) {
                //是FactoryBean的话直接在beanName之前加&获取到bean
                Object bean = getBean(FACTORY_BEAN_PREFIX + beanName);
                //保险起见,再判断一次
                if (bean instanceof FactoryBean) {
                    //强转为FactoryBean
                    final FactoryBean<?> factory = (FactoryBean<?>) bean;
                    boolean isEagerInit;
                    //如果是SmartFactoryBean的实例,下面的判断确定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());
                    }
                    //如果需要立刻初始化,就调用getBean方法
                    if (isEagerInit) {
                        getBean(beanName);
                    }
                }
            }
            else {
                //如果是普通bean,直接调用getBean方法就可以了
                getBean(beanName);
            }
        }
    }
    //截止到这里beanDefinition就变成了bean并注册了。

    //如果我们定义的bean实现SmartInitializingSingleton接口,
    //就执行afterSingletonsInstantiated方法
    for (String beanName : beanNames) {
        Object singletonInstance = getSingleton(beanName);
        if (singletonInstance instanceof SmartInitializingSingleton) {
            final SmartInitializingSingleton smartSingleton = (SmartInitializingSingleton) singletonInstance;
            if (System.getSecurityManager() != null) {
                AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
                    smartSingleton.afterSingletonsInstantiated();
                    return null;
                }, getAccessControlContext());
            }
            else {
                smartSingleton.afterSingletonsInstantiated();
            }
        }
    }
}

2、我们继续看38行的getBean方法,进入其父类AbstractBeanFactory中的getBean方法

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

3、继续看doGetBean

//AbstractBeanFactory
/**
 * do开头的方法是真正做事的方法,getBean方法是为了从容器中获取bean用的
 * 如果已经初始化过的直接会返回,如果没有初始化的会先初始化再返回,所以该方法也可以用于初始化
 */
@SuppressWarnings("unchecked")
protected <T> T doGetBean(final String name, @Nullable final Class<T> requiredType,
        @Nullable final Object[] args, boolean typeCheckOnly) throws BeansException {
	//这边处理两种情况
    //1、FactoryBean(前面带 ‘&’),把前面的&去除
    //2、传进来的名字是别名,转成正式的名字
    final String beanName = transformedBeanName(name);
    Object bean;

    // 检查下缓存中是否已经存在单例bean
    Object sharedInstance = getSingleton(beanName);
    //这里说下args,虽然看上去一点不重要。前面我们一路进来的时候都是getBean(beanName),
    //所以args传参其实是null,但是如果args不为空,那么意味着调用方不是希望获取Bean,而是创建Bean
    if (sharedInstance != null && args == null) {
        if (logger.isTraceEnabled()) {
            if (isSingletonCurrentlyInCreation(beanName)) {
                logger.trace("Returning eagerly cached instance of singleton bean '" + beanName +
                        "' that is not fully initialized yet - a consequence of a circular reference");
            }
            else {
                logger.trace("Returning cached instance of singleton bean '" + beanName + "'");
            }
        }
        //下面判断sharedInstance有没有实现FactoryBean接口,
        //如果没有实现,说明是普通bean,直接返回就行。
        //如果实现了FactoryBean接口,返回它创建的那个实例对象
        bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);
    }

    else {
        //如果我们已经在创建此bean实例,则失败:
		//我们可以肯定地在一个循环引用中。
        if (isPrototypeCurrentlyInCreation(beanName)) {
            throw new BeanCurrentlyInCreationException(beanName);
        }

        //检查一下这个BeanDefinition在容器中是否存在
        BeanFactory parentBeanFactory = getParentBeanFactory();
        if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
            //如果当前容器不存在这个BeanDefinition,试试父容器中有没有
            String nameToLookup = originalBeanName(name);
            if (parentBeanFactory instanceof AbstractBeanFactory) {
                //返回父容器的查询结果
                return ((AbstractBeanFactory) parentBeanFactory).doGetBean(
                        nameToLookup, requiredType, args, typeCheckOnly);
            }
            else if (args != null) {
                return (T) parentBeanFactory.getBean(nameToLookup, args);
            }
            else if (requiredType != null) {
                return parentBeanFactory.getBean(nameToLookup, requiredType);
            }
            else {
                return (T) parentBeanFactory.getBean(nameToLookup);
            }
        }

        if (!typeCheckOnly) {
            //typeCheckOnly为false,将当前beanName放入一个alreadyCreated的Set集合中
            markBeanAsCreated(beanName);
        }

        try {
            //取出beanDefinition
            final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
            //检查一下
            checkMergedBeanDefinition(mbd, beanName, args);

            //这里的依赖指的是depends-on中定义的依赖
            String[] dependsOn = mbd.getDependsOn();
            if (dependsOn != null) {
                for (String dep : dependsOn) {
                    if (isDependent(beanName, dep)) {
                        throw new BeanCreationException(mbd.getResourceDescription(), beanName,
                                "Circular depends-on relationship between '" + beanName + "' and '" + dep + "'");
                    }
                    //注册一下依赖关系
                    registerDependentBean(dep, beanName);
                    try {
                        //先初始化被依赖项
                        getBean(dep);
                    }
                    catch (NoSuchBeanDefinitionException ex) {
                        throw new BeanCreationException(mbd.getResourceDescription(), beanName,
                                "'" + beanName + "' depends on missing bean '" + dep + "'", ex);
                    }
                }
            }

            //如果scope是singleton,创建singleton实例
            if (mbd.isSingleton()) {
                //先createBean()创建 bean,再getSingleton()将bean拿出来
                sharedInstance = getSingleton(beanName, () -> {
                    try {
                        //创建bean,后面展开说
                        return createBean(beanName, mbd, args);
                    }
                    catch (BeansException ex) {
                        //如果创建出现异常就销毁bean
                        destroySingleton(beanName);
                        throw ex;
                    }
                });
                //同32行getObjectForBeanInstance
                bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
            }

            //如果scope是prototype,创建prototype实例
            else if (mbd.isPrototype()) {
                //创建一个新的实例
                Object prototypeInstance = null;
                try {
                    beforePrototypeCreation(beanName);
                    prototypeInstance = createBean(beanName, mbd, args);
                }
                finally {
                    afterPrototypeCreation(beanName);
                }
                //同32行getObjectForBeanInstance
                bean = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);
            }
        	//如果不是singleton和prototype的话,需要委托给相应的实现类来处理
            else {
                String scopeName = mbd.getScope();
                final Scope scope = this.scopes.get(scopeName);
                if (scope == null) {
                    throw new IllegalStateException("No Scope registered for scope name '" + scopeName + "'");
                }
                try {
                    Object scopedInstance = scope.get(beanName, () -> {
                        beforePrototypeCreation(beanName);
                        try {
                            return createBean(beanName, mbd, args);
                        }
                        finally {
                            afterPrototypeCreation(beanName);
                        }
                    });
                    //同32行getObjectForBeanInstance
                    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;
        }
    }

    //最后,检查一下类型对不对,不对的话就抛异常,对的话就返回
    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;
}

4、重点看下98行-108行,getSingleton方法传入了一个Lamda表达式,里面一段代码,这段代码在什么时候执行呢,我们先看下getSingleton方法,进入类DefaultSingletonBeanRegistry中

//DefaultSingletonBeanRegistry
/**
 * 返回单例对象,如果没有就创建后再返回
 */
public Object getSingleton(String beanName, ObjectFactory<?> singletonFactory) {
    Assert.notNull(beanName, "Bean name must not be null");
    synchronized (this.singletonObjects) {
        //先尝试从一层缓存中获取完整的bean对象
        Object singletonObject = this.singletonObjects.get(beanName);
        if (singletonObject == null) {
            //如果不存在
            if (this.singletonsCurrentlyInDestruction) {
                throw new BeanCreationNotAllowedException(beanName,
                        "Singleton bean creation not allowed while singletons of this factory are in destruction " +
                        "(Do not request a bean from a BeanFactory in a destroy method implementation!)");
            }
            if (logger.isDebugEnabled()) {
                logger.debug("Creating shared instance of singleton bean '" + beanName + "'");
            }
            beforeSingletonCreation(beanName);
            boolean newSingleton = false;
            boolean recordSuppressedExceptions = (this.suppressedExceptions == null);
            if (recordSuppressedExceptions) {
                this.suppressedExceptions = new LinkedHashSet<>();
            }
            //这里就是创建单例对象
            try {
                //这里调用的是入参中Lamda表达式中的代码块,也就是createBean,
                //返回值赋值给singletonObject
                singletonObject = singletonFactory.getObject();
                newSingleton = true;
            }
            catch (IllegalStateException ex) {
                singletonObject = this.singletonObjects.get(beanName);
                if (singletonObject == null) {
                    throw ex;
                }
            }
            catch (BeanCreationException ex) {
                if (recordSuppressedExceptions) {
                    for (Exception suppressedException : this.suppressedExceptions) {
                        ex.addRelatedCause(suppressedException);
                    }
                }
                throw ex;
            }
            finally {
                if (recordSuppressedExceptions) {
                    this.suppressedExceptions = null;
                }
                afterSingletonCreation(beanName);
            }
            if (newSingleton) {
                //放入一级缓存中
                addSingleton(beanName, singletonObject);
            }
        }
        return singletonObject;
    }
}

其中singletonFactory.getObject();调用的其实是传进来的Lamda表达式中的代码块,我们点击createBean方法,进入子类AbstractAutowireCapableBeanFactory的createBean方法中

//AbstractAutowireCapableBeanFactory
/**
 * 这个类的核心方法: 创建一个bean实例,
 * 填充bean实例,应用后处理器等。
 */
@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;

    Class<?> resolvedClass = resolveBeanClass(mbd, beanName);
    if (resolvedClass != null && !mbd.hasBeanClass() && mbd.getBeanClassName() != null) {
        mbdToUse = new RootBeanDefinition(mbd);
        mbdToUse.setBeanClass(resolvedClass);
    }

    //准备方法覆写,这里又涉及到一个概念:
    //MethodOverrides,它来自于bean定义中的<lookup-method />和<replaced-method />
    try {
        mbdToUse.prepareMethodOverrides();
    }
    catch (BeanDefinitionValidationException ex) {
        throw new BeanDefinitionStoreException(mbdToUse.getResourceDescription(),
                beanName, "Validation of method overrides failed", ex);
    }

    try {
        //让BeanPostProcessors有机会返回代理而不是目标bean实例。
        Object bean = resolveBeforeInstantiation(beanName, mbdToUse);
        if (bean != null) {
            return bean;
        }
    }
    catch (Throwable ex) {
        throw new BeanCreationException(mbdToUse.getResourceDescription(), beanName,
                "BeanPostProcessor before instantiation of bean failed", ex);
    }

    try {
        //创建实例,重点
        Object beanInstance = doCreateBean(beanName, mbdToUse, args);
        if (logger.isTraceEnabled()) {
            logger.trace("Finished creating instance of bean '" + beanName + "'");
        }
        return beanInstance;
    }
    catch (BeanCreationException | ImplicitlyAppearedSingletonException ex) {
        throw ex;
    }
    catch (Throwable ex) {
        throw new BeanCreationException(
                mbdToUse.getResourceDescription(), beanName, "Unexpected exception during bean creation", ex);
    }
}

5、继续点击46行的doCreateBean进去

//AbstractAutowireCapableBeanFactory
/**
 * 实际上创建指定的bean
 */
protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final @Nullable Object[] args)
        throws BeanCreationException {

    //bean的包装类对象
    BeanWrapper instanceWrapper = null;
    if (mbd.isSingleton()) {
        instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
    }
    if (instanceWrapper == null) {
        //这里实例化Bean
        instanceWrapper = createBeanInstance(beanName, mbd, args);
    }
    //从包装类对象里取出bean
    final Object bean = instanceWrapper.getWrappedInstance();
	//从包装类对象里取出bean的类型
    Class<?> beanType = instanceWrapper.getWrappedClass();
    if (beanType != NullBean.class) {
        //如果不是空类型,赋值到resolvedTargetType
        mbd.resolvedTargetType = beanType;
    }

    //允许后处理器修改合并的bean定义。
    synchronized (mbd.postProcessingLock) {
        if (!mbd.postProcessed) {
            try {
                applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
            }
            catch (Throwable ex) {
                throw new BeanCreationException(mbd.getResourceDescription(), beanName,
                        "Post-processing of merged bean definition failed", ex);
            }
            mbd.postProcessed = true;
        }
    }

    //下面这块代码是为了解决循环依赖的问题
    boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences &&
            isSingletonCurrentlyInCreation(beanName));
    if (earlySingletonExposure) {
        if (logger.isTraceEnabled()) {
            logger.trace("Eagerly caching bean '" + beanName +
                    "' to allow for resolving potential circular references");
        }
        //放入三级缓存
        addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
    }

    //前面只是创建了bean实例,现在要初始化bean实例
    Object exposedObject = bean;
    try {
        //重点,进行属性装配,给bean实例设置属性
        populateBean(beanName, mbd, instanceWrapper);
        //执行init方法和bean后处理器,一会展开讲
        exposedObject = initializeBean(beanName, exposedObject, mbd);
    }
    catch (Throwable ex) {
        if (ex instanceof BeanCreationException && beanName.equals(((BeanCreationException) ex).getBeanName())) {
            throw (BeanCreationException) ex;
        }
        else {
            throw new BeanCreationException(
                    mbd.getResourceDescription(), beanName, "Initialization of bean failed", ex);
        }
    }

    if (earlySingletonExposure) {
        Object earlySingletonReference = getSingleton(beanName, false);
        if (earlySingletonReference != null) {
            if (exposedObject == bean) {
                exposedObject = earlySingletonReference;
            }
            else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) {
                String[] dependentBeans = getDependentBeans(beanName);
                Set<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 " +
                            "'getBeanNamesOfType' with the 'allowEagerInit' flag turned off, for example.");
                }
            }
        }
    }

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

    return exposedObject;
}

6、上面这步里有3个重要的方法分别是createBeanInstance、populateBean、initializeBean,下面我们先看createBeanInstance

//AbstractAutowireCapableBeanFactory
/**
 * 创建bean实例
 */
protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) {
    //确保bean类在此时已实际解析。
    Class<?> beanClass = resolveBeanClass(mbd, beanName);

    //校验一下这个类的访问权限
    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());
    }

    Supplier<?> instanceSupplier = mbd.getInstanceSupplier();
    if (instanceSupplier != null) {
        return obtainFromSupplier(instanceSupplier, beanName);
    }

    if (mbd.getFactoryMethodName() != null) {
        //采用工厂方法实例化
        return instantiateUsingFactoryMethod(beanName, mbd, args);
    }

    //如果不是第一次创建,比如prototype的bean。
    //我们可以从第一次创建知道,采用无参构造函数,还是构造函数依赖注入来完成实例化
    boolean resolved = false;
    boolean autowireNecessary = false;
    if (args == null) {
        synchronized (mbd.constructorArgumentLock) {
            if (mbd.resolvedConstructorOrFactoryMethod != null) {
                resolved = true;
                autowireNecessary = mbd.constructorArgumentsResolved;
            }
        }
    }
    if (resolved) {
        if (autowireNecessary) {
            //构造函数依赖注入
            return autowireConstructor(beanName, mbd, null, null);
        }
        else {
            //无参构造函数
            return instantiateBean(beanName, mbd);
        }
    }

    //判断是否采用有参构造函数
    Constructor<?>[] ctors = determineConstructorsFromBeanPostProcessors(beanClass, beanName);
    if (ctors != null || mbd.getResolvedAutowireMode() == AUTOWIRE_CONSTRUCTOR ||
            mbd.hasConstructorArgumentValues() || !ObjectUtils.isEmpty(args)) {
        return autowireConstructor(beanName, mbd, ctors, args);
    }

    //构造函数依赖注入
    ctors = mbd.getPreferredConstructors();
    if (ctors != null) {
        return autowireConstructor(beanName, mbd, ctors, null);
    }

    //调用无参构造函数
    return instantiateBean(beanName, mbd);
}

7、再来看populateBean

//AbstractAutowireCapableBeanFactory 
/**
 * 使用bean定义中的属性值填充给定BeanWrapper中的bean实例。
 */
@SuppressWarnings("deprecation")
protected void populateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw) {
    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;
        }
    }

    boolean continueWithPropertyPopulation = true;

    if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
        //获取所有后置处理器开始处理
        for (BeanPostProcessor bp : getBeanPostProcessors()) {
            if (bp instanceof InstantiationAwareBeanPostProcessor) {
                InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
                //判断不需要后置处理的话直接返回
                if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {
                    continueWithPropertyPopulation = false;
                    break;
                }
            }
        }
    }

    if (!continueWithPropertyPopulation) {
        return;
    }

    //获取所有属性值
    PropertyValues pvs = (mbd.hasPropertyValues() ? mbd.getPropertyValues() : null);

    //判断注入的方式是根据名字注入,还是根据类型进行注入
    if (mbd.getResolvedAutowireMode() == AUTOWIRE_BY_NAME || mbd.getResolvedAutowireMode() == AUTOWIRE_BY_TYPE) {
        MutablePropertyValues newPvs = new MutablePropertyValues(pvs);
        //通过名字装配
        if (mbd.getResolvedAutowireMode() == AUTOWIRE_BY_NAME) {
            autowireByName(beanName, mbd, bw, newPvs);
        }
        //通过类型装配
        if (mbd.getResolvedAutowireMode() == AUTOWIRE_BY_TYPE) {
            autowireByType(beanName, mbd, bw, newPvs);
        }
        pvs = newPvs;
    }

    boolean hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors();
    boolean needsDepCheck = (mbd.getDependencyCheck() != AbstractBeanDefinition.DEPENDENCY_CHECK_NONE);

    PropertyDescriptor[] filteredPds = null;
    if (hasInstAwareBpps) {
        if (pvs == null) {
            pvs = mbd.getPropertyValues();
        }
        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);
                    }
                    //这里有个非常有用的BeanPostProcessor,
                    //AutowiredAnnotationBeanPostProcessor
                    //对采用@Autowired、@Value注解的依赖进行设值
                    pvsToUse = ibp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName);
                    if (pvsToUse == null) {
                        return;
                    }
                }
                pvs = pvsToUse;
            }
        }
    }
    if (needsDepCheck) {
        if (filteredPds == null) {
            filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
        }
        checkDependencies(beanName, mbd, filteredPds, pvs);
    }

    if (pvs != null) {
        //设置bean实例的属性值
        applyPropertyValues(beanName, mbd, bw, pvs);
    }
}

8、再来看initializeBean

//AbstractAutowireCapableBeanFactory
/**
 * 执行init方法和bean后处理器。(各种回调)
 */
protected Object initializeBean(final String beanName, final Object bean, @Nullable RootBeanDefinition mbd) {
    if (System.getSecurityManager() != null) {
        AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
            invokeAwareMethods(beanName, bean);
            return null;
        }, getAccessControlContext());
    }
    else {
        //如果bean实现了BeanNameAware、BeanClassLoaderAware或BeanFactoryAware接口,回调
        invokeAwareMethods(beanName, bean);
    }

    Object wrappedBean = bean;
    if (mbd == null || !mbd.isSynthetic()) {
        //BeanPostProcessor的postProcessBeforeInitialization回调
        wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
    }

    try {
        //处理bean中定义的init-method
      	//如果bean实现了InitializingBean接口,调用afterPropertiesSet()方法
        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()) {
        //BeanPostProcessor的postProcessAfterInitialization回调
        //AOP后置处理器在这里
        wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
    }

    return wrappedBean;
}

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/154510.html

(0)
飞熊的头像飞熊bm

相关推荐

发表回复

登录后才能评论
极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!