Spring IoC源码学习:createBean 详解(下)

目录

Spring IoC源码学习全系列

前言

正文

doCreateBean

代码块1:applyMergedBeanDefinitionPostProcessors

代码块2:addSingletonFactory

代码块3:getEarlyBeanReference

代码块4:populateBean

代码块5:autowireByName

代码块6:unsatisfiedNonSimpleProperties

代码块7:isSimpleProperty

代码块8:containsBean

代码块9:autowireByType

代码块10:applyPropertyValues

代码块11:initializeBean

代码块12:invokeAwareMethods

代码块13:applyBeanPostProcessorsBeforeInitialization

代码块14:postProcessBeforeInitialization

代码块15:invokeInitMethods

代码块16:invokeCustomInitMethod

代码块17:applyBeanPostProcessorsAfterInitialization

代码块18:registerDisposableBeanIfNecessary

代码块19:requiresDestruction

代码块20:hasDestroyMethod

代码块21:hasApplicableProcessors

代码块22:DisposableBeanAdapter

代码块23:inferDestroyMethodIfNecessary

代码块24:filterPostProcessors

总结

相关文章


Spring IoC源码学习全系列

小白也看得懂的 Spring IoC 核心流程介绍

Spring IoC源码学习:总览

Spring IoC源码学习:ApplicationContext 刷新前的配置

Spring IoC源码学习:obtainFreshBeanFactory详解

Spring IoC源码学习:parseDefaultElement详解

Spring IoC源码学习:parseCustomElement详解

Spring IoC源码学习:obtainFreshBeanFactory详解

Spring IoC源码学习:invokeBeanFactoryPostProcessors详解

Spring IoC源码学习:registerBeanPostProcessors详解

Spring IoC源码学习:finishBeanFactoryInitialization详解

Spring IoC源码学习:getBean详解

Spring IoC源码学习:createBean详解(上)

Spring IoC源码学习:createBean详解(下)

Spring IoC源码学习:@Autowire 详解

Spring IoC源码学习:finishRefresh 详解

 

前言

接着 Spring IoC:createBean详解(上),我们继续解析创建 bean 实例的剩下内容。

 

正文

首先,我们回到 Spring IoC:createBean详解(上)中的代码块3,doCreateBean 方法。

 

doCreateBean

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

    // Instantiate the bean.
    // 1.新建Bean包装类
    BeanWrapper instanceWrapper = null;
    if (mbd.isSingleton()) {
        // 2.如果是FactoryBean,则需要先移除未完成的FactoryBean实例的缓存
        instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
    }
    if (instanceWrapper == null) {
        // 3.根据beanName、mbd、args,使用对应的策略创建Bean实例,并返回包装类BeanWrapper
        instanceWrapper = createBeanInstance(beanName, mbd, args);
    }
    // 4.拿到创建好的Bean实例
    final Object bean = (instanceWrapper != null ? instanceWrapper.getWrappedInstance() : null);
    // 5.拿到Bean实例的类型
    Class<?> beanType = (instanceWrapper != null ? instanceWrapper.getWrappedClass() : null);
    mbd.resolvedTargetType = beanType;

    // Allow post-processors to modify the merged bean definition.
    synchronized (mbd.postProcessingLock) {
        if (!mbd.postProcessed) {
            try {
                // 6.应用后置处理器MergedBeanDefinitionPostProcessor,允许修改MergedBeanDefinition,
                // Autowired注解正是通过此方法实现注入类型的预解析
                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.
    // 7.判断是否需要提早曝光实例:单例 && 允许循环依赖 && 当前bean正在创建中
    boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences &&
            isSingletonCurrentlyInCreation(beanName));
    if (earlySingletonExposure) {
        if (logger.isDebugEnabled()) {
            logger.debug("Eagerly caching bean '" + beanName +
                    "' to allow for resolving potential circular references");
        }

        // 8.提前曝光beanName的ObjectFactory,用于解决循环引用
        addSingletonFactory(beanName, new ObjectFactory<Object>() {
            @Override
            public Object getObject() throws BeansException {
                // 8.1 应用后置处理器SmartInstantiationAwareBeanPostProcessor,允许返回指定bean的早期引用,若没有则直接返回bean
                return getEarlyBeanReference(beanName, mbd, bean);
            }
        });
    }

    // Initialize the bean instance.  初始化bean实例。
    Object exposedObject = bean;
    try {
        // 9.对bean进行属性填充;其中,可能存在依赖于其他bean的属性,则会递归初始化依赖的bean实例
        populateBean(beanName, mbd, instanceWrapper);
        if (exposedObject != null) {
            // 10.对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) {
        // 11.如果允许提前曝光实例,则进行循环依赖检查
        Object earlySingletonReference = getSingleton(beanName, false);
        // 11.1 earlySingletonReference只有在当前解析的bean存在循环依赖的情况下才会不为空
        if (earlySingletonReference != null) {
            if (exposedObject == bean) {
                // 11.2 如果exposedObject没有在initializeBean方法中被增强,则不影响之前的循环引用
                exposedObject = earlySingletonReference;
            } else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) {
                // 11.3 如果exposedObject在initializeBean方法中被增强 && 不允许在循环引用的情况下使用注入原始bean实例
                // && 当前bean有被其他bean依赖

                // 11.4 拿到依赖当前bean的所有bean的beanName数组
                String[] dependentBeans = getDependentBeans(beanName);
                Set<String> actualDependentBeans = new LinkedHashSet<String>(dependentBeans.length);
                for (String dependentBean : dependentBeans) {
                    // 11.5 尝试移除这些bean的实例,因为这些bean依赖的bean已经被增强了,他们依赖的bean相当于脏数据
                    if (!removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) {
                        // 11.6 移除失败的添加到 actualDependentBeans
                        actualDependentBeans.add(dependentBean);
                    }
                }

                if (!actualDependentBeans.isEmpty()) {
                    // 11.7 如果存在移除失败的,则抛出异常,因为存在bean依赖了“脏数据”
                    throw new BeanCurrentlyInCreationException(beanName,
                            "Bean with name '" + beanName + "' has been injected into other beans [" +
                                    StringUtils.collectionToCommaDelimitedString(actualDependentBeans) +
                                    "] in its raw version as part of a circular reference, but has eventually been " +
                                    "wrapped. This means that said other beans do not use the final version of the " +
                                    "bean. This is often the result of over-eager type matching - consider using " +
                                    "'getBeanNamesOfType' with the 'allowEagerInit' flag turned off, for example.");
                }
            }
        }
    }

    // Register bean as disposable.
    try {
        // 12.注册用于销毁的bean,执行销毁操作的有三种:自定义destroy方法、DisposableBean接口、DestructionAwareBeanPostProcessor
        registerDisposableBeanIfNecessary(beanName, bean, mbd);
    } catch (BeanDefinitionValidationException ex) {
        throw new BeanCreationException(
                mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex);
    }
    // 13.完成创建并返回
    return exposedObject;
}

3.根据 beanName、mbd、args,使用对应的策略创建 bean 实例,并返回包装类 BeanWrapper,见 Spring IoC:createBean详解(上)中的代码块3

6.应用后置处理器 MergedBeanDefinitionPostProcessor,允许修改 MergedBeanDefinition,见代码块1详解

8.提前曝光 beanName 的 ObjectFactory,用于解决循环引用,见代码块2详解

8.1 应用后置处理器 SmartInstantiationAwareBeanPostProcessor,允许返回指定 bean 的早期引用,见代码块3详解

9.对 bean 进行属性填充;其中,可能存在依赖于其他 bean 的属性,则会递归初始化依赖的 bean 实例,见代码块4详解

10.对 bean 进行初始化,见代码块11详解

11.1 earlySingletonReference 只有在当前解析的 bean 存在循环依赖的情况下才会不为空。

因为如果不是循环依赖,只会在完全创建完 bean 实例才会添加到 singletonObjects 缓存。此时,我们正在创建 bean 的过程中,还没有完全创建完,singletonObjects 缓存是肯定没有当前 beanName 的;而如果不存在循环引用,从 doGetBean 方法开始,getSingleton 方法只会在最初 doGetBean 方法里调用一次,不存在循环引用,也就用不到提前曝光的 ObjectFactory 来创建 bean 对象,从而 earlySingletonObjects 缓存肯定也是没有 beanName 的 bean 实例对象的,所以必然返回空。

12.注册用于销毁的 bean,执行销毁操作的有三种:自定义 destroy 方法、DisposableBean 接口、DestructionAwareBeanPostProcessor,见代码块18详解

 

代码块1:applyMergedBeanDefinitionPostProcessors

protected void applyMergedBeanDefinitionPostProcessors(RootBeanDefinition mbd, Class<?> beanType, String beanName) {
    // 1.获取BeanFactory中已注册的BeanPostProcessor
    for (BeanPostProcessor bp : getBeanPostProcessors()) {
        if (bp instanceof MergedBeanDefinitionPostProcessor) {
            // 2.调用MergedBeanDefinitionPostProcessor的postProcessMergedBeanDefinition方法,
            // 对指定bean的给定MergedBeanDefinition进行后置处理,@Autowire注解在这边对元数据进行预解析
            MergedBeanDefinitionPostProcessor bdp = (MergedBeanDefinitionPostProcessor) bp;
            bdp.postProcessMergedBeanDefinition(mbd, beanType, beanName);
        }
    }
}

调用 MergedBeanDefinitionPostProcessor 的 postProcessMergedBeanDefinition 方法,对指定 bean 的给定MergedBeanDefinition进行后置处理,@Autowire 注解在这边对元数据进行预解析,之后会单独介绍。

 

代码块2:addSingletonFactory

protected void addSingletonFactory(String beanName, ObjectFactory<?> singletonFactory) {
    Assert.notNull(singletonFactory, "Singleton factory must not be null");
    synchronized (this.singletonObjects) {
        // 1.如果beanName不存在于singletonObjects缓存中
        if (!this.singletonObjects.containsKey(beanName)) {
            // 2.将beanName和singletonFactory注册到singletonFactories缓存(beanName -> 该beanName的单例工厂)
            this.singletonFactories.put(beanName, singletonFactory);
            // 3.移除earlySingletonObjects缓存中的beanName(beanName -> beanName的早期单例对象)
            this.earlySingletonObjects.remove(beanName);
            // 4.将beanName注册到registeredSingletons缓存(已经注册的单例集合)
            this.registeredSingletons.add(beanName);
        }
    }
}

在 Spring IoC:finishBeanFactoryInitialization详解 中的代码块7,我们通过提前曝光的 ObjectFactory 获得 “不完整” 的 bean 实例,从而解决循环引用的问题,ObjectFactory 就是通过这边的 singletonObjects 缓存来进行曝光的。

 

代码块3:getEarlyBeanReference

protected Object getEarlyBeanReference(String beanName, RootBeanDefinition mbd, Object bean) {
    Object exposedObject = bean;
    // 1.如果bean不为空 && mbd不是合成 && 存在InstantiationAwareBeanPostProcessors
    if (bean != null && !mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
        for (BeanPostProcessor bp : getBeanPostProcessors()) {
            // 2.应用所有SmartInstantiationAwareBeanPostProcessor,调用getEarlyBeanReference方法
            if (bp instanceof SmartInstantiationAwareBeanPostProcessor) {
                SmartInstantiationAwareBeanPostProcessor ibp = (SmartInstantiationAwareBeanPostProcessor) bp;
                // 3.允许SmartInstantiationAwareBeanPostProcessor返回指定bean的早期引用
                exposedObject = ibp.getEarlyBeanReference(exposedObject, beanName);
                if (exposedObject == null) {
                    return null;
                }
            }
        }
    }
    // 4.返回要作为bean引用公开的对象,如果没有SmartInstantiationAwareBeanPostProcessor修改,则返回的是入参的bean对象本身
    return exposedObject;
}

 

代码块4:populateBean

protected void populateBean(String beanName, RootBeanDefinition mbd, BeanWrapper bw) {
    // 1.返回此bean的属性值
    PropertyValues pvs = mbd.getPropertyValues();

    // 2.bw为空时的处理
    if (bw == null) {
        if (!pvs.isEmpty()) {
            // 2.1 如果bw为空,属性不为空,抛异常,无法将属性值应用于null实例
            throw new BeanCreationException(
                    mbd.getResourceDescription(), beanName, "Cannot apply property values to null instance");
        } else {
            // Skip property population phase for null instance.
            // 2.2 如果bw为空,属性也为空,则跳过
            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.
    // 用于标识是否继续之后的属性填充
    boolean continueWithPropertyPopulation = true;

    if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
        // 3.1 如果mbd不是合成的 && 存在InstantiationAwareBeanPostProcessor,则遍历处理InstantiationAwareBeanPostProcessor
        for (BeanPostProcessor bp : getBeanPostProcessors()) {
            if (bp instanceof InstantiationAwareBeanPostProcessor) {
                InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
                // 3.2 在bean实例化后,属性填充之前被调用,允许修改bean的属性,如果返回false,则跳过之后的属性填充
                if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {
                    // 3.3 如果返回false,将continueWithPropertyPopulation赋值为false,代表要跳过之后的属性填充
                    continueWithPropertyPopulation = false;
                    break;
                }
            }
        }
    }
    // 3.4 如果continueWithPropertyPopulation为false,则跳过之后的属性填充
    if (!continueWithPropertyPopulation) {
        return;
    }

    // 4.解析自动装配模式为AUTOWIRE_BY_NAME和AUTOWIRE_BY_TYPE(现在几乎不用)
    if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_NAME ||
            mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_TYPE) {
        MutablePropertyValues newPvs = new MutablePropertyValues(pvs);

        if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_NAME) {
            // 4.1 解析autowireByName的注入
            autowireByName(beanName, mbd, bw, newPvs);
        }

        if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_TYPE) {
            // 4.2 解析autowireByType的注入
            autowireByType(beanName, mbd, bw, newPvs);
        }
        pvs = newPvs;
    }

    // 5.BeanFactory是否注册过InstantiationAwareBeanPostProcessors
    boolean hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors();
    // 6.是否需要依赖检查
    boolean needsDepCheck = (mbd.getDependencyCheck() != RootBeanDefinition.DEPENDENCY_CHECK_NONE);

    // 7.注册过InstantiationAwareBeanPostProcessors 或者 需要依赖检查
    if (hasInstAwareBpps || needsDepCheck) {
        PropertyDescriptor[] filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
        if (hasInstAwareBpps) {
            // 7.1 应用后置处理器InstantiationAwareBeanPostProcessor
            for (BeanPostProcessor bp : getBeanPostProcessors()) {
                if (bp instanceof InstantiationAwareBeanPostProcessor) {
                    InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
                    // 7.1.1 应用后置处理器InstantiationAwareBeanPostProcessor的方法postProcessPropertyValues,
                    // 进行属性填充前的再次处理。例子:现在最常用的@Autowire属性注入就是这边注入依赖的bean实例对象
                    pvs = ibp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName);
                    if (pvs == null) {
                        return;
                    }
                }
            }
        }
        if (needsDepCheck) {
            // 7.2 依赖检查,对应depends-on属性
            checkDependencies(beanName, mbd, filteredPds, pvs);
        }
    }

    // 8.将所有PropertyValues中的属性填充到bean中
    applyPropertyValues(beanName, mbd, bw, pvs);
}

4.1 解析 autowireByName 的注入,见代码块5详解

4.2 解析 autowireByType 的注入,见代码块9详解

7.1.1 应用后置处理器 InstantiationAwareBeanPostProcessor 的方法 postProcessPropertyValues,进行属性填充前的再次处理。现在最常用的 @Autowire 属性注入就是这边注入依赖的 bean 实例对象,具体实现在 AutowiredAnnotationBeanPostProcessor,该内容会在之后介绍 @Autowire 的文章中单独介绍。

8.将所有 PropertyValues 中的属性填充到 bean 中,见代码块10详解

 

代码块5:autowireByName

protected void autowireByName(
        String beanName, AbstractBeanDefinition mbd, BeanWrapper bw, MutablePropertyValues pvs) {

    // 1.寻找bw中需要依赖注入的属性
    String[] propertyNames = unsatisfiedNonSimpleProperties(mbd, bw);
    for (String propertyName : propertyNames) {
        // 2.校验是否存在beanName=propertyName的bean实例或者BeanDefinition
        if (containsBean(propertyName)) {
            // 3.获取propertyName的bean实例对象
            Object bean = getBean(propertyName);
            // 4.将属性名和属性值添加到pvs
            pvs.add(propertyName, bean);
            // 5.注册依赖关系到缓存(beanName依赖propertyName)
            registerDependentBean(propertyName, beanName);
            if (logger.isDebugEnabled()) {
                logger.debug("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");
            }
        }
    }
}

1.寻找 bw 中需要依赖注入的属性,见代码块6详解

2.校验是否存在 beanName = propertyName 的 bean 实例或者 BeanDefinition,见代码块8详解

5.注册依赖关系到缓存(beanName 依赖 propertyName),见 Spring IoC:getBean详解 中代码块7详解

 

autowireByName 的使用例子

Spring 配置:

<!-- 8.autowireByName -->
<bean id="fruit" class="com.joonwhee.open.demo.simple.Fruit" autowire="byName">
    <property name="color" value="Red"/>
</bean>
<!-- id值跟Fruit里的属性名一致 -->
<bean id="apple" class="com.joonwhee.open.demo.simple.Apple"/>

Fruit 对象:

public class Fruit {

    private Apple apple;

    private String color;

    public Apple getApple() {
        return apple;
    }

    public void setApple(Apple apple) {
        this.apple = apple;
    }

    public String getColor() {
        return color;
    }

    public void setColor(String color) {
        this.color = color;
    }
}

 

代码块6:unsatisfiedNonSimpleProperties

protected String[] unsatisfiedNonSimpleProperties(AbstractBeanDefinition mbd, BeanWrapper bw) {
    Set<String> result = new TreeSet<String>();
    // 1.拿到mdb的属性值
    PropertyValues pvs = mbd.getPropertyValues();
    // 2.拿到bw的PropertyDescriptors
    PropertyDescriptor[] pds = bw.getPropertyDescriptors();
    // 3.遍历bw的PropertyDescriptors
    for (PropertyDescriptor pd : pds) {
        // 4.pd用于写入属性值的方法不为空 && pd不是从依赖性检查中排除的bean属性 && pd不包含在pvs里
        // && pd的属性类型不是“简单”属性(基础类型、枚举、Number等)
        // 4.1 isSimpleProperty: 判断属性是不是“简单”属性
        if (pd.getWriteMethod() != null && !isExcludedFromDependencyCheck(pd) && !pvs.contains(pd.getName()) &&
                !BeanUtils.isSimpleProperty(pd.getPropertyType())) {
            // 4.2 符合条件,则添加pd的name到result中
            result.add(pd.getName());
        }
    }
    return StringUtils.toStringArray(result);
}

4.1 isSimpleProperty:判断属性是不是 “简单” 属性,见代码块7详解

 

代码块7:isSimpleProperty

public static boolean isSimpleProperty(Class<?> clazz) {
    Assert.notNull(clazz, "Class must not be null");
    // clazz是简单值类型 || ( clazz是数组 && clazz的组件类型为简单值类型)
    // getComponentType:返回数组的组件类型,例如: String[] 返回 String.class,如果是非数组,则返回null
    return isSimpleValueType(clazz) || (clazz.isArray() && isSimpleValueType(clazz.getComponentType()));
}

public static boolean isSimpleValueType(Class<?> clazz) {
    return (ClassUtils.isPrimitiveOrWrapper(clazz) || clazz.isEnum() ||
            CharSequence.class.isAssignableFrom(clazz) ||
            Number.class.isAssignableFrom(clazz) ||
            Date.class.isAssignableFrom(clazz) ||
            URI.class == clazz || URL.class == clazz ||
            Locale.class == clazz || Class.class == clazz);
}

// ClassUtils.java
public static boolean isPrimitiveOrWrapper(Class<?> clazz) {
    Assert.notNull(clazz, "Class must not be null");
    // clazz为基础类型 或者 clazz是基础类型的封装类
    return (clazz.isPrimitive() || isPrimitiveWrapper(clazz));
}

public static boolean isPrimitiveWrapper(Class<?> clazz) {
    Assert.notNull(clazz, "Class must not be null");
    // 检查clazz是否为8种基础类型的包装类
    // primitiveWrapperTypeMap缓存包含8种基础类型和包装类的映射,例如:Integer.class -> int.class
    return primitiveWrapperTypeMap.containsKey(clazz);
}

static {
    primitiveWrapperTypeMap.put(Boolean.class, boolean.class);
    primitiveWrapperTypeMap.put(Byte.class, byte.class);
    primitiveWrapperTypeMap.put(Character.class, char.class);
    primitiveWrapperTypeMap.put(Double.class, double.class);
    primitiveWrapperTypeMap.put(Float.class, float.class);
    primitiveWrapperTypeMap.put(Integer.class, int.class);
    primitiveWrapperTypeMap.put(Long.class, long.class);
    primitiveWrapperTypeMap.put(Short.class, short.class);

    // ...
}

 

代码块8:containsBean

@Override
public boolean containsBean(String name) {
    // 1.将name转换为真正的beanName
    String beanName = transformedBeanName(name);
    // 2.检查singletonObjects缓存和beanDefinitionMap缓存中是否存在beanName
    if (containsSingleton(beanName) || containsBeanDefinition(beanName)) {
        // 3.name不带&前缀,或者是FactoryBean,则返回true
        return (!BeanFactoryUtils.isFactoryDereference(name) || isFactoryBean(name));
    }
    // Not found -> check parent.
    // 4.没有找到则检查parentBeanFactory
    BeanFactory parentBeanFactory = getParentBeanFactory();
    return (parentBeanFactory != null && parentBeanFactory.containsBean(originalBeanName(name)));
}

 

代码块9:autowireByType

protected void autowireByType(
        String beanName, AbstractBeanDefinition mbd, BeanWrapper bw, MutablePropertyValues pvs) {

    TypeConverter converter = getCustomTypeConverter();
    if (converter == null) {
        converter = bw;
    }

    Set<String> autowiredBeanNames = new LinkedHashSet<String>(4);
    // 1.寻找bw中需要依赖注入的属性
    String[] propertyNames = unsatisfiedNonSimpleProperties(mbd, bw);
    // 2.遍历所有需要依赖注入的属性
    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.
            if (Object.class != pd.getPropertyType()) {
                // 3.获取指定属性的set方法,封装成MethodParameter(必须有set方法才能通过属性来注入)
                MethodParameter methodParam = BeanUtils.getWriteMethodParameter(pd);
                // Do not allow eager init for type matching in case of a prioritized post-processor.
                boolean eager = !PriorityOrdered.class.isAssignableFrom(bw.getWrappedClass());
                // 4.将MethodParameter的方法参数索引信息封装成DependencyDescriptor
                DependencyDescriptor desc = new AutowireByTypeDependencyDescriptor(methodParam, eager);
                // 5.解析当前属性所匹配的bean实例,并把解析到的bean实例的beanName存储在autowiredBeanNames中
                Object autowiredArgument = resolveDependency(desc, beanName, autowiredBeanNames, converter);
                if (autowiredArgument != null) {
                    // 6.如果找到了依赖的bean实例,将属性名和bean实例放到pvs中
                    pvs.add(propertyName, autowiredArgument);
                }
                for (String autowiredBeanName : autowiredBeanNames) {
                    // 7.注册依赖关系,beanName依赖autowiredBeanName
                    registerDependentBean(autowiredBeanName, beanName);
                    if (logger.isDebugEnabled()) {
                        logger.debug("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);
        }
    }
}

1.寻找 bw 中需要依赖注入的属性,见代码块6详解

5.解析当前属性所匹配的 bean 实例,并把解析到的 bean 实例的 beanName 存储在 autowiredBeanNames 中,见 Spring IoC:createBean详解(上) 中代码块9详解

7.注册依赖关系,beanName 依赖 autowiredBeanName,见 Spring IoC:getBean详解 中代码块7详解

 

autowireByType 的使用例子

Spring 配置:

<bean id="fruit" class="com.joonwhee.open.demo.simple.Fruit" autowire="byType">
    <property name="color" value="Red"/>
</bean>
<!-- id值随便取,fruit中的apple属性通过类型匹配 -->
<bean id="uselessName" class="com.joonwhee.open.demo.simple.Apple"/>

Fruit 对象:

public class Fruit {

    private Apple apple;

    private String color;

    public Apple getApple() {
        return apple;
    }

    public void setApple(Apple apple) {
        this.apple = apple;
    }

    public String getColor() {
        return color;
    }

    public void setColor(String color) {
        this.color = color;
    }
}

 

代码块10:applyPropertyValues

protected void applyPropertyValues(String beanName, BeanDefinition mbd, BeanWrapper bw, PropertyValues pvs) {
    if (pvs == null || pvs.isEmpty()) {
        return;
    }

    MutablePropertyValues mpvs = null;
    List<PropertyValue> original;

    if (System.getSecurityManager() != null) {
        if (bw instanceof BeanWrapperImpl) {
            ((BeanWrapperImpl) bw).setSecurityContext(getAccessControlContext());
        }
    }

    // 1.获取属性值列表
    if (pvs instanceof MutablePropertyValues) {
        mpvs = (MutablePropertyValues) pvs;
        // 1.1 如果mpvs中的值已经被转换为对应的类型,那么可以直接设置到BeanWrapper中
        if (mpvs.isConverted()) {
            // Shortcut: use the pre-converted values as-is.
            try {
                bw.setPropertyValues(mpvs);
                return;
            } catch (BeansException ex) {
                throw new BeanCreationException(
                        mbd.getResourceDescription(), beanName, "Error setting property values", ex);
            }
        }
        original = mpvs.getPropertyValueList();
    } else {
        // 1.2 如果pvs并不是使用MutablePropertyValues封装的类型,那么直接使用原始的属性获取方法
        original = Arrays.asList(pvs.getPropertyValues());
    }

    TypeConverter converter = getCustomTypeConverter();
    if (converter == null) {
        converter = bw;
    }
    // 2.1 获取对应的解析器
    BeanDefinitionValueResolver valueResolver = new BeanDefinitionValueResolver(this, beanName, mbd, converter);

    // Create a deep copy, resolving any references for values.
    // 2.2 创建深层拷贝副本,用于存放解析后的属性值
    List<PropertyValue> deepCopy = new ArrayList<PropertyValue>(original.size());
    boolean resolveNecessary = false;
    // 3.遍历属性,将属性转换为对应类的对应属性的类型
    for (PropertyValue pv : original) {
        if (pv.isConverted()) {
            // 3.1 如果pv已经包含转换的值,则直接添加到deepCopy
            deepCopy.add(pv);
        } else {
            // 3.2 否则,进行转换
            // 3.2.1 拿到pv的原始属性名和属性值
            String propertyName = pv.getName();
            Object originalValue = pv.getValue();
            // 3.2.2 使用解析器解析原始属性值
            Object resolvedValue = valueResolver.resolveValueIfNecessary(pv, originalValue);
            Object convertedValue = resolvedValue;
            // 3.2.3 判断该属性是否可转换
            boolean convertible = bw.isWritableProperty(propertyName) &&
                    !PropertyAccessorUtils.isNestedOrIndexedProperty(propertyName);
            if (convertible) {
                // 3.2.4 如果可转换,则转换指定目标属性的给定值
                convertedValue = convertForProperty(resolvedValue, propertyName, bw, converter);
            }
            // Possibly store converted value in merged bean definition,
            // in order to avoid re-conversion for every created bean instance.
            // 3.2.5 在合并的BeanDefinition中存储转换后的值,以避免为每个创建的bean实例重新转换
            if (resolvedValue == originalValue) {
                if (convertible) {
                    pv.setConvertedValue(convertedValue);
                }
                deepCopy.add(pv);
            } else if (convertible && originalValue instanceof TypedStringValue &&
                    !((TypedStringValue) originalValue).isDynamic() &&
                    !(convertedValue instanceof Collection || ObjectUtils.isArray(convertedValue))) {
                pv.setConvertedValue(convertedValue);
                deepCopy.add(pv);
            } else {
                resolveNecessary = true;
                deepCopy.add(new PropertyValue(pv, convertedValue));
            }
        }
    }
    if (mpvs != null && !resolveNecessary) {
        mpvs.setConverted();
    }

    // Set our (possibly massaged) deep copy.
    try {
        // 4.设置bean的属性值为deepCopy
        bw.setPropertyValues(new MutablePropertyValues(deepCopy));
    } catch (BeansException ex) {
        throw new BeanCreationException(
                mbd.getResourceDescription(), beanName, "Error setting property values", ex);
    }
}

 

代码块11:initializeBean

protected Object initializeBean(final String beanName, final Object bean, RootBeanDefinition mbd) {
    // 1.激活Aware方法
    if (System.getSecurityManager() != null) {
        AccessController.doPrivileged(new PrivilegedAction<Object>() {
            @Override
            public Object run() {
                invokeAwareMethods(beanName, bean);
                return null;
            }
        }, getAccessControlContext());
    } else {
        invokeAwareMethods(beanName, bean);
    }

    Object wrappedBean = bean;
    if (mbd == null || !mbd.isSynthetic()) {
        // 2.在初始化前应用BeanPostProcessor的postProcessBeforeInitialization方法,允许对bean实例进行包装
        wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
    }

    try {
        // 3.调用初始化方法
        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()) {
        // 4.在初始化后应用BeanPostProcessor的postProcessAfterInitialization方法,允许对bean实例进行包装
        wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
    }
    // 5.返回wrappedBean
    return wrappedBean;
}

1.激活 Aware方法,见代码块12详解

2.在初始化前应用后置处理器 BeanPostProcessor 的 postProcessBeforeInitialization 方法,允许对 bean 实例进行包装,见代码块13详解

3.调用初始化方法,见代码块15详解

4.在初始化后应用后置处理器 BeanPostProcessor 的 postProcessAfterInitialization 方法,允许对 bean 实例进行包装,见代码块17详解

 

代码块12:invokeAwareMethods

private void invokeAwareMethods(final String beanName, final Object bean) {
    if (bean instanceof Aware) {
        // BeanNameAware: 实现此接口的类想要拿到beanName,因此我们在这边赋值给它
        if (bean instanceof BeanNameAware) {
            ((BeanNameAware) bean).setBeanName(beanName);
        }
        // BeanClassLoaderAware:实现此接口的类想要拿到beanClassLoader,因此我们在这边赋值给它
        if (bean instanceof BeanClassLoaderAware) {
            ((BeanClassLoaderAware) bean).setBeanClassLoader(getBeanClassLoader());
        }
        // BeanFactoryAware: 实现此接口的类想要拿到 BeanFactory,因此我们在这边赋值给它
        if (bean instanceof BeanFactoryAware) {
            ((BeanFactoryAware) bean).setBeanFactory(AbstractAutowireCapableBeanFactory.this);
        }
    }
}

如果对 Spring 比较熟悉的同学应该知道,以 Aware 为结尾的类都是一些扩展接口,用于提供给开发者获取到 BeanFactory 中的一些属性或对象。

 

代码块13:applyBeanPostProcessorsBeforeInitialization

@Override
public Object applyBeanPostProcessorsBeforeInitialization(Object existingBean, String beanName)
        throws BeansException {

    Object result = existingBean;
    // 1.遍历所有注册的BeanPostProcessor实现类,调用postProcessBeforeInitialization方法
    for (BeanPostProcessor beanProcessor : getBeanPostProcessors()) {
        // 2.在bean初始化方法执行前,调用postProcessBeforeInitialization方法
        result = beanProcessor.postProcessBeforeInitialization(result, beanName);
        if (result == null) {
            return result;
        }
    }
    return result;
}

在 bean 初始化前,调用所有 BeanPostProcessors 的 postProcessBeforeInitialization 方法,这个在很早之前就说过了。这边提一个比较重要的实现类:ApplicationContextAwareProcessor,见代码块14详解

 

代码块14:postProcessBeforeInitialization

@Override
public Object postProcessBeforeInitialization(final Object bean, String beanName) throws BeansException {
    AccessControlContext acc = null;

    if (System.getSecurityManager() != null &&
            (bean instanceof EnvironmentAware || bean instanceof EmbeddedValueResolverAware ||
                    bean instanceof ResourceLoaderAware || bean instanceof ApplicationEventPublisherAware ||
                    bean instanceof MessageSourceAware || bean instanceof ApplicationContextAware)) {
        acc = this.applicationContext.getBeanFactory().getAccessControlContext();
    }

    if (acc != null) {
        AccessController.doPrivileged(new PrivilegedAction<Object>() {
            @Override
            public Object run() {
                invokeAwareInterfaces(bean);
                return null;
            }
        }, acc);
    }
    else {
        // 调用Aware接口
        invokeAwareInterfaces(bean);
    }

    return bean;
}

private void invokeAwareInterfaces(Object bean) {
    if (bean instanceof Aware) {
        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);
        }
        // ApplicationContextAware:实现此接口的类想要拿到ApplicationContext,因此我们在这边赋值给它
        if (bean instanceof ApplicationContextAware) {
            ((ApplicationContextAware) bean).setApplicationContext(this.applicationContext);
        }
    }
}

我们经常通过实现 ApplicationContextAware 接口来拿到 ApplicationContext,我们之所以能拿到 ApplicationContext,就是在这边被赋值的。

 

代码块15:invokeInitMethods

protected void invokeInitMethods(String beanName, final Object bean, RootBeanDefinition mbd)
        throws Throwable {

    // 1.首先检查bean是否实现了InitializingBean接口,如果是的话调用afterPropertiesSet方法
    boolean isInitializingBean = (bean instanceof InitializingBean);
    if (isInitializingBean && (mbd == null || !mbd.isExternallyManagedInitMethod("afterPropertiesSet"))) {
        if (logger.isDebugEnabled()) {
            logger.debug("Invoking afterPropertiesSet() on bean with name '" + beanName + "'");
        }
        // 2.调用afterPropertiesSet方法
        if (System.getSecurityManager() != null) {
            try {
                AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() {
                    @Override
                    public Object run() throws Exception {
                        ((InitializingBean) bean).afterPropertiesSet();
                        return null;
                    }
                }, getAccessControlContext());
            } catch (PrivilegedActionException pae) {
                throw pae.getException();
            }
        } else {
            ((InitializingBean) bean).afterPropertiesSet();
        }
    }

    if (mbd != null) {
        String initMethodName = mbd.getInitMethodName();
        if (initMethodName != null && !(isInitializingBean && "afterPropertiesSet".equals(initMethodName)) &&
                !mbd.isExternallyManagedInitMethod(initMethodName)) {
            // 3.调用自定义初始化方法
            invokeCustomInitMethod(beanName, bean, mbd);
        }
    }
}

2.调用自定义初始化方法,见代码块16详解

 

代码块16:invokeCustomInitMethod

protected void invokeCustomInitMethod(String beanName, final Object bean, RootBeanDefinition mbd)
        throws Throwable {
    // 1.拿到初始化方法的方法名
    String initMethodName = mbd.getInitMethodName();
    // 2.根据方法名拿到方法
    final Method initMethod = (mbd.isNonPublicAccessAllowed() ?
            BeanUtils.findMethod(bean.getClass(), initMethodName) :
            ClassUtils.getMethodIfAvailable(bean.getClass(), initMethodName));
    if (initMethod == null) {
        // 3.如果不存在initMethodName对应的方法,并且是强制执行初始化方法(默认为强制), 则抛出异常
        if (mbd.isEnforceInitMethod()) {
            throw new BeanDefinitionValidationException("Couldn't find an init method named '" +
                    initMethodName + "' on bean with name '" + beanName + "'");
        } else {    // 如果设置了非强制,找不到则直接返回
            if (logger.isDebugEnabled()) {
                logger.debug("No default init method named '" + initMethodName +
                        "' found on bean with name '" + beanName + "'");
            }
            // Ignore non-existent default lifecycle methods.
            return;
        }
    }

    if (logger.isDebugEnabled()) {
        logger.debug("Invoking init method  '" + initMethodName + "' on bean with name '" + beanName + "'");
    }

    // 4.调用初始化方法
    if (System.getSecurityManager() != null) {
        AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() {
            @Override
            public Object run() throws Exception {
                ReflectionUtils.makeAccessible(initMethod);
                return null;
            }
        });
        try {
            AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() {
                @Override
                public Object run() throws Exception {
                    initMethod.invoke(bean);
                    return null;
                }
            }, getAccessControlContext());
        } catch (PrivilegedActionException pae) {
            InvocationTargetException ex = (InvocationTargetException) pae.getException();
            throw ex.getTargetException();
        }
    } else {
        try {
            ReflectionUtils.makeAccessible(initMethod);
            initMethod.invoke(bean);
        } catch (InvocationTargetException ex) {
            throw ex.getTargetException();
        }
    }
}

 

代码块17:applyBeanPostProcessorsAfterInitialization

@Override
public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName)
        throws BeansException {

    Object result = existingBean;
    // 1.遍历所有注册的BeanPostProcessor实现类,调用postProcessAfterInitialization方法
    for (BeanPostProcessor beanProcessor : getBeanPostProcessors()) {
        // 2.在bean初始化方法执行后,调用postProcessAfterInitialization方法
        result = beanProcessor.postProcessAfterInitialization(result, beanName);
        if (result == null) {
            return result;
        }
    }
    return result;
}

 

代码块18:registerDisposableBeanIfNecessary

protected void registerDisposableBeanIfNecessary(String beanName, Object bean, RootBeanDefinition mbd) {
    AccessControlContext acc = (System.getSecurityManager() != null ? getAccessControlContext() : null);
    // 1.mbd的scope不是prototype && 给定的bean需要在关闭时销毁
    if (!mbd.isPrototype() && requiresDestruction(bean, mbd)) {
        if (mbd.isSingleton()) {
            // 2.单例模式下注册用于销毁的bean到disposableBeans缓存,执行给定bean的所有销毁工作:
            // DestructionAwareBeanPostProcessors,DisposableBean接口,自定义销毁方法
            // 2.1 DisposableBeanAdapter:使用DisposableBeanAdapter来封装用于销毁的bean
            registerDisposableBean(beanName,
                    new DisposableBeanAdapter(bean, beanName, mbd, getBeanPostProcessors(), acc));
        } else {
            // 3.自定义scope处理
            // A bean with a custom scope...
            Scope scope = this.scopes.get(mbd.getScope());
            if (scope == null) {
                throw new IllegalStateException("No Scope registered for scope name '" + mbd.getScope() + "'");
            }
            scope.registerDestructionCallback(beanName,
                    new DisposableBeanAdapter(bean, beanName, mbd, getBeanPostProcessors(), acc));
        }
    }
}

1.requiresDestruction(bean, mbd):判断给定的 bean 是否需要在关闭时销毁,见代码块19详解

2.1 使用 DisposableBeanAdapter 来封装用于销毁的 bean,见代码块22详解

 

代码块19:requiresDestruction

protected boolean requiresDestruction(Object bean, RootBeanDefinition mbd) {
    // 1.DisposableBeanAdapter.hasDestroyMethod(bean, mbd):判断bean是否有destroy方法
    // 2.hasDestructionAwareBeanPostProcessors():判断当前BeanFactory是否注册过DestructionAwareBeanPostProcessor
    // 3.DisposableBeanAdapter.hasApplicableProcessors:是否存在适用于bean的DestructionAwareBeanPostProcessor
    return (bean != null &&
            (DisposableBeanAdapter.hasDestroyMethod(bean, mbd) || (hasDestructionAwareBeanPostProcessors() &&
                    DisposableBeanAdapter.hasApplicableProcessors(bean, getBeanPostProcessors()))));
}

1.DisposableBeanAdapter.hasDestroyMethod(bean, mbd):判断 bean 是否有 destroy 方法,见代码块20详解

3.DisposableBeanAdapter.hasApplicableProcessors:是否存在适用于 bean 的 DestructionAwareBeanPostProcessor,见代码块21详解

 

代码块20:hasDestroyMethod

public static boolean hasDestroyMethod(Object bean, RootBeanDefinition beanDefinition) {
    if (bean instanceof DisposableBean || closeableInterface.isInstance(bean)) {
        // 1.如果bean实现了DisposableBean接口 或者 bean是AutoCloseable实例,则返回true
        return true;
    }
    // 2.拿到bean自定义的destroy方法名
    String destroyMethodName = beanDefinition.getDestroyMethodName();
    if (AbstractBeanDefinition.INFER_METHOD.equals(destroyMethodName)) {
        // 3.如果自定义的destroy方法名为“(inferred)”(该名字代表需要我们自己去推测destroy的方法名),
        // 则检查该bean是否存在方法名为“close”或“shutdown”的方法,如果存在,则返回true
        return (ClassUtils.hasMethod(bean.getClass(), CLOSE_METHOD_NAME) ||
                ClassUtils.hasMethod(bean.getClass(), SHUTDOWN_METHOD_NAME));
    }
    // 4.如果destroyMethodName不为空,则返回true
    return StringUtils.hasLength(destroyMethodName);
}

1.如果 bean 实现了 DisposableBean 接口或 bean 是 AutoCloseable 实例,则返回 true,因为这两个接口都有关闭的方法。

 

代码块21:hasApplicableProcessors

public static boolean hasApplicableProcessors(Object bean, List<BeanPostProcessor> postProcessors) {
    if (!CollectionUtils.isEmpty(postProcessors)) {
        // 1.遍历所有的BeanPostProcessor
        for (BeanPostProcessor processor : postProcessors) {
            // 2.如果processor是DestructionAwareBeanPostProcessor
            if (processor instanceof DestructionAwareBeanPostProcessor) {
                DestructionAwareBeanPostProcessor dabpp = (DestructionAwareBeanPostProcessor) processor;
                try {
                    if (dabpp.requiresDestruction(bean)) {
                        // 3.如果给定的bean实例需要通过此后处理器进行销毁,则返回true
                        return true;
                    }
                }
                catch (AbstractMethodError err) {
                    // A pre-4.3 third-party DestructionAwareBeanPostProcessor...
                    // As of 5.0, we can let requiresDestruction be a Java 8 default method which returns true.
                    return true;
                }
            }
        }
    }
    return false;
}

 

代码块22:DisposableBeanAdapter

public DisposableBeanAdapter(Object bean, String beanName, RootBeanDefinition beanDefinition,
                             List<BeanPostProcessor> postProcessors, AccessControlContext acc) {

    Assert.notNull(bean, "Disposable bean must not be null");
    this.bean = bean;
    this.beanName = beanName;
    // 1.判断bean是否需要调用DisposableBean的destroy方法
    this.invokeDisposableBean =
            (this.bean instanceof DisposableBean && !beanDefinition.isExternallyManagedDestroyMethod("destroy"));
    this.nonPublicAccessAllowed = beanDefinition.isNonPublicAccessAllowed();
    this.acc = acc;
    // 2.拿到自定义的destroy方法名
    String destroyMethodName = inferDestroyMethodIfNecessary(bean, beanDefinition);
    if (destroyMethodName != null && !(this.invokeDisposableBean && "destroy".equals(destroyMethodName)) &&
            !beanDefinition.isExternallyManagedDestroyMethod(destroyMethodName)) {
        this.destroyMethodName = destroyMethodName;
        // 3.拿到自定义的destroy方法,赋值给this.destroyMethod
        this.destroyMethod = determineDestroyMethod();
        if (this.destroyMethod == null) {
            if (beanDefinition.isEnforceDestroyMethod()) {
                // 4.如果destroy方法名为空,并且enforceDestroyMethod为true,则抛出异常
                throw new BeanDefinitionValidationException("Couldn't find a destroy method named '" +
                        destroyMethodName + "' on bean with name '" + beanName + "'");
            }
        } else {
            // 5.拿到destroy方法的参数类型数组
            Class<?>[] paramTypes = this.destroyMethod.getParameterTypes();
            if (paramTypes.length > 1) {
                // 6.如果destroy方法的参数大于1个,则抛出异常
                throw new BeanDefinitionValidationException("Method '" + destroyMethodName + "' of bean '" +
                        beanName + "' has more than one parameter - not supported as destroy method");
            } else if (paramTypes.length == 1 && boolean.class != paramTypes[0]) {
                // 7.如果destroy方法的参数为1个,并且该参数的类型不为boolean,则抛出异常
                throw new BeanDefinitionValidationException("Method '" + destroyMethodName + "' of bean '" +
                        beanName + "' has a non-boolean parameter - not supported as destroy method");
            }
        }
    }
    // 8.查找DestructionAwareBeanPostProcessors,并赋值给this.beanPostProcessors
    this.beanPostProcessors = filterPostProcessors(postProcessors, bean);
}

2.拿到自定义的 destroy 方法名,见代码块23详解

8.查找 DestructionAwareBeanPostProcessors,并赋值给 beanPostProcessors,见代码块24详解

 

代码块23:inferDestroyMethodIfNecessary

private String inferDestroyMethodIfNecessary(Object bean, RootBeanDefinition beanDefinition) {
    // 1.拿到beanDefinition的destroy方法名
    String destroyMethodName = beanDefinition.getDestroyMethodName();
    // 2.如果destroy方法名为“(inferred)”|| destroyMethodName为null,并且bean是AutoCloseable实例
    if (AbstractBeanDefinition.INFER_METHOD.equals(destroyMethodName) ||
            (destroyMethodName == null && closeableInterface.isInstance(bean))) {
        // Only perform destroy method inference or Closeable detection
        // in case of the bean not explicitly implementing DisposableBean
        // 3.如果bean没有实现DisposableBean接口,则尝试推测destroy方法的名字
        if (!(bean instanceof DisposableBean)) {
            try {
                // 4.尝试在bean中寻找方法名为close的方法作为destroy方法
                return bean.getClass().getMethod(CLOSE_METHOD_NAME).getName();
            } catch (NoSuchMethodException ex) {
                try {
                    // 5.尝试在bean中寻找方法名为close的方法作为shutdown方法
                    return bean.getClass().getMethod(SHUTDOWN_METHOD_NAME).getName();
                } catch (NoSuchMethodException ex2) {
                    // no candidate destroy method found
                }
            }
        }
        // 6.如果没有找到,则返回null
        return null;
    }
    return (StringUtils.hasLength(destroyMethodName) ? destroyMethodName : null);
}

 

代码块24:filterPostProcessors

private List<DestructionAwareBeanPostProcessor> filterPostProcessors(List<BeanPostProcessor> processors, Object bean) {
    List<DestructionAwareBeanPostProcessor> filteredPostProcessors = null;
    if (!CollectionUtils.isEmpty(processors)) {
        filteredPostProcessors = new ArrayList<DestructionAwareBeanPostProcessor>(processors.size());
        // 1.遍历所有的BeanPostProcessor
        for (BeanPostProcessor processor : processors) {
            // 2.如果processor是DestructionAwareBeanPostProcessor
            if (processor instanceof DestructionAwareBeanPostProcessor) {
                DestructionAwareBeanPostProcessor dabpp = (DestructionAwareBeanPostProcessor) processor;
                try {
                    if (dabpp.requiresDestruction(bean)) {
                        // 3.如果给定的bean实例需要通过此后处理器进行销毁,则添加到filteredPostProcessors
                        filteredPostProcessors.add(dabpp);
                    }
                } catch (AbstractMethodError err) {
                    // A pre-4.3 third-party DestructionAwareBeanPostProcessor...
                    // As of 5.0, we can let requiresDestruction be a Java 8 default method which returns true.
                    filteredPostProcessors.add(dabpp);
                }
            }
        }
    }
    return filteredPostProcessors;
}

 

总结

至此,finishBeanFactoryInitialization 方法解析完毕,我们通过 Spring IoC:finishBeanFactoryInitialization详解Spring IoC:getBean详解Spring IoC:createBean详解(上)和本文共四篇文章来介绍 finishBeanFactoryInitialization 方法。在 finishBeanFactoryInitialization 方法中,我们主要做了以下操作:

  • 将之前解析的 BeanDefinition 进一步处理,将有父 BeanDefinition 的进行合并,获得 MergedBeanDefinition
  • 尝试从缓存获取 bean 实例
  • 处理特殊的 bean —— FactoryBean 的创建
  • 创建 bean 实例
  • 循环引用的处理
  • bean 实例属性填充
  • bean 实例的初始化
  • BeanPostProcessor 的各种扩展应用

finishBeanFactoryInitialization 方法解析的结束,也标志着 Spring IoC 整个构建过程中,重要的内容基本都已经解析完毕。由于工程较为浩大,因此整个系列的文章中,肯定会有各种各样的问题:理解错误的、用词不一致的(有时候用 “BeanDefinition”,有时候用 “bean 定义”)、漏掉的等等,后续如果有时间,可能会在抽空完善一下,尽量减少出现的问题,也欢迎各位同学指正文章中的错误。

另外,本系列文章到目前为止都是单纯的解析 Spring IoC 的源码,之后可能会再补充一些重要的内容,例如:本文提到要写的@Autowire 注解的依赖注入过程、Spring IoC 中的核心类的介绍等。

 

程序员囧辉 CSDN认证博客专家 Spring MySQL 分布式
当你的才华还撑不起你的野心的时候,你就应该静下心来学习,愿你在我这里能有所收获。公众号:程序员囧辉,分享个人在Java学习路上的一些学习、思考、经验和总结。
©️2020 CSDN 皮肤主题: 数字20 设计师: CSDN官方博客 返回首页
实付0元
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值