天天看点

Spring IoC createBean 方法详解

前言

本篇文章主要分析 Spring IoC 的

createBean()

方法的流程,以及

bean

的生命周期。

下面是一个大致的流程图:

正文

AbstractAutowireCapableBeanFactory#createBean

@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.
    // 将String类型的class字符串,转换为Class对象,例如在XML中配置的class属性
    Class<?> resolvedClass = resolveBeanClass(mbd, beanName);
    if (resolvedClass != null && !mbd.hasBeanClass() && mbd.getBeanClassName() != null) {
        mbdToUse = new RootBeanDefinition(mbd);
        mbdToUse.setBeanClass(resolvedClass);
    }

    // Prepare method overrides.
    try {
        // 进行定义的方法覆盖
        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.
        // 如果bean的实例化前回调方法返回非null,直接返回实例,跳过后面步骤
        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 {
        // 真正去创建bean的方法
        Object beanInstance = doCreateBean(beanName, mbdToUse, args);
        if (logger.isTraceEnabled()) {
            logger.trace("Finished creating instance of bean '" + beanName + "'");
        }
        // 返回bean的实例
        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);
    }
}
           

上面方法如果

resolveBeforeInstantiation()

返回非

null

,则会跳过后面步骤,直接返回实例。这也是一个扩展点,给

BeanPostProcessor

一个机会来返回代理来替代真正的实例。

AbstractAutowireCapableBeanFactory#resolveBeforeInstantiation

protected Object resolveBeforeInstantiation(String beanName, RootBeanDefinition mbd) {
    Object bean = null;
    // 判断bean在实例化之前是否已经解析过
    if (!Boolean.FALSE.equals(mbd.beforeInstantiationResolved)) {
        // Make sure bean class is actually resolved at this point.
        // 如果bean是合成的 && 有实现 InstantiationAwareBeanPostProcessor 接口
        if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
            // 解析bean的类型
            Class<?> targetType = determineTargetType(beanName, mbd);
            if (targetType != null) {
                // 执行bean的实例化前回调
                bean = applyBeanPostProcessorsBeforeInstantiation(targetType, beanName);
                // 如果实例化前生命周期回调方法返回的不是null
                if (bean != null) {
                    // 执行bean的实例化后回调,因为只能在此处调用了
                    bean = applyBeanPostProcessorsAfterInitialization(bean, beanName);
                }
            }
        }
        // 如果bean不为空,则将beforeInstantiationResolved赋值为true,代表在实例化之前已经解析
        mbd.beforeInstantiationResolved = (bean != null);
    }
    return bean;
}
           

上面方法主要是判断

bean

之前没有解析过并且有注册

InstantiationAwareBeanPostProcessor

接口,然后这里会调用

bean

实例化前的回调方法,如果返回非空,会调用

bean

实例化后的回调方法;因为返回非空,后续正常的流程都不会走了,所以只能在此处调用。

下面是

InstantiationAwareBeanPostProcessor

接口,如下:

public interface InstantiationAwareBeanPostProcessor extends BeanPostProcessor {

    /**
    * Bean 实例化前调用,返回非 {@code null} 回调过后面流程
    * 返回 {@code null} 则进行 IoC 容器对 Bean 的实例化
    */
    @Nullable
    default Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) throws BeansException {
        return null;
    }

    /**
    * Bean 实例化之后,属性填充之前调用,返回 {@code true} 则进行默认的属性填充步骤,
    * 返回 {@code false} 会跳过属性填充阶段,同样也会跳过初始化阶段的生命周期方法的回调。
    */
    default boolean postProcessAfterInstantiation(Object bean, String beanName) throws BeansException {
        return true;
    }

    /**
    * Bean 实例化后属性赋值前调用,PropertyValues 是已经封装好的设置的属性值,返回 {@code null} 继续
    */
    @Nullable
    default PropertyValues postProcessProperties(PropertyValues pvs, Object bean, String beanName) throws BeansException {
        return null;
    }

    /**
    * 5.1 版本后已经被上面 postProcessProperties 方法所替代,功能与上面方法一样
    */
	@Deprecated
	@Nullable
	default PropertyValues postProcessPropertyValues(
			PropertyValues pvs, PropertyDescriptor[] pds, Object bean, String beanName) throws BeansException {
		return pvs;
	}

}
           

上面接口提供了三个扩展点,如下:

  • bean

    实例化前
  • bean

    实例化后
  • bean

    属性赋值前

这也是

bean

实例化的生命周期回调方法。

AbstractAutowireCapableBeanFactory#doCreateBean

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

    // Instantiate the bean.
    BeanWrapper instanceWrapper = null;
    if (mbd.isSingleton()) {
        // 如果bean的作用域是singleton,则需要移除未完成的FactoryBean实例的缓存
        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) {
        mbd.resolvedTargetType = beanType;
    }

    // Allow post-processors to modify the merged bean definition.
    synchronized (mbd.postProcessingLock) {
        if (!mbd.postProcessed) {
            try {
                // BeanDefinition 合并后的回调,见下文详解
                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正在创建中
    boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences && isSingletonCurrentlyInCreation(beanName));
    // 如果允许bean提前曝光
    if (earlySingletonExposure) {
        if (logger.isTraceEnabled()) {
            logger.trace("Eagerly caching bean '" + beanName +
                         "' to allow for resolving potential circular references");
        }
        // 将beanName和ObjectFactory形成的key-value对放入singletonFactories缓存中
        addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
    }

    // Initialize the bean instance.
    Object exposedObject = bean;
    try {
        // 给 bean 的属性赋值
        populateBean(beanName, mbd, instanceWrapper);
        // 初始化 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);
        }
    }
    // 如果允许单例bean提前暴露
    if (earlySingletonExposure) {
        Object earlySingletonReference = getSingleton(beanName, false);
        // 只有在检测到循环依赖的情况下才不为空
        if (earlySingletonReference != null) {
            // 如果exposedObject没有在初始化方法中被改变,也就是没有被增强
            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.");
                }
            }
        }
    }

    // Register bean as disposable.
    try {
        // 用于注册销毁bean
        registerDisposableBeanIfNecessary(beanName, bean, mbd);
    } catch (BeanDefinitionValidationException ex) {
        throw new BeanCreationException(
            mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex);
    }
    // 返回bean实例
    return exposedObject;
}
           

AbstractAutowireCapableBeanFactory#createBeanInstance

/**
* @param args	  getBean() 中的 args 参数
* @return 		  bean 实例包装后的 BeanWrapper
*/
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);
    // 判断beanClass是否是public修饰的类,并且是否允许访问非公共构造函数和方法,不是抛出异常
    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());
    }
    // Spring 5新添加的,如果存在Supplier回调,则使用给定的回调方法初始化策略。可以使RootBeanDefinition#setInstanceSupplier()设置
    Supplier<?> instanceSupplier = mbd.getInstanceSupplier();
    if (instanceSupplier != null) {
        return obtainFromSupplier(instanceSupplier, beanName);
    }
    // 如果设置工厂方法则使用给定的方法创建bean实例,这里分为静态工厂和实例化工厂
    if (mbd.getFactoryMethodName() != null) {
        return instantiateUsingFactoryMethod(beanName, mbd, args);
    }

    // Shortcut when re-creating the same bean...
    // resolved: 构造函数或工厂方法是否已经解析过
    boolean resolved = false;
    // autowireNecessary: 是否需要自动注入 (即是否需要解析构造函数)
    boolean autowireNecessary = false;
    if (args == null) {
        synchronized (mbd.constructorArgumentLock) {
            // 如果resolvedConstructorOrFactoryMethod不为空,代表构造函数或工厂方法已经解析过
            if (mbd.resolvedConstructorOrFactoryMethod != null) {
                resolved = true;
                // 根据constructorArgumentsResolved判断是否需要自动注入
                autowireNecessary = mbd.constructorArgumentsResolved;
            }
        }
    }
    if (resolved) {
        if (autowireNecessary) {
            // 如果构造函数或工厂方法已经解析过并且需要自动注入,则执行构造器自动注入,见下文详解
            return autowireConstructor(beanName, mbd, null, null);
        }
        else {
            // 否则使用默认构造函数进行bean实例化,见下文详解
            return instantiateBean(beanName, mbd);
        }
    }

    // Candidate constructors for autowiring?
    // 应用后置处理器,SmartInstantiationAwareBeanPostProcessor 拿到 bean 的候选构造函数
    Constructor<?>[] ctors = determineConstructorsFromBeanPostProcessors(beanClass, beanName);
    // 候选构造函数不为空 || 构造函数依赖注入 || 定义了构造函数的参数值 || args不为空,则执行构造器自动注入
    if (ctors != null || mbd.getResolvedAutowireMode() == AUTOWIRE_CONSTRUCTOR ||
        mbd.hasConstructorArgumentValues() || !ObjectUtils.isEmpty(args)) {
        return autowireConstructor(beanName, mbd, ctors, args);
    }

    // Preferred constructors for default construction?
    // 如果有首选的构造函数,使用该构造函数去创建bean实例
    ctors = mbd.getPreferredConstructors();
    if (ctors != null) {
        return autowireConstructor(beanName, mbd, ctors, null);
    }

    // No special handling: simply use no-arg constructor.
    // 没有特殊处理,使用默认无参构造器实例化bean
    return instantiateBean(beanName, mbd);
}
           

上面代码主要判断是使用构函数自动注入,还是使用默认构造函数构造。总结起来以下几种情况会使用构造函数自动注入:

  • 已经缓存过构造函数并且构造函数的参数已经解析过。
  • 候选的构造函数不为空,这里的候选构造函数是通过实现

    SmartInstantiationAwareBeanPostProcessor

    接口中的

    determineCandidateConstructors()

  • 自动注入模式为构造函数自动注入
  • BeanDefinition

    定义了构造函数参数,如 XML 中的

    <constructor-arg index="0" value="1"/>

  • 在调用

    getBean()

    时显示指定了

    args

    参数

AbstractAutowireCapableBeanFactory#instantiateBean

protected BeanWrapper instantiateBean(final String beanName, final RootBeanDefinition mbd) {
    try {
        Object beanInstance;
        final BeanFactory parent = this;
        if (System.getSecurityManager() != null) {
            beanInstance = AccessController.doPrivileged((PrivilegedAction<Object>) () ->
                                                         getInstantiationStrategy().instantiate(mbd, beanName, parent),
                                                         getAccessControlContext());
        }
        else {
            // 使用指定的策略去实力化bean
            beanInstance = getInstantiationStrategy().instantiate(mbd, beanName, parent);
        }
        // 将实例化后的bean封装成BeanWrapper后返回
        BeanWrapper bw = new BeanWrapperImpl(beanInstance);
        initBeanWrapper(bw);
        return bw;
    }
    catch (Throwable ex) {
        throw new BeanCreationException(
            mbd.getResourceDescription(), beanName, "Instantiation of bean failed", ex);
    }
}

// SimpleInstantiationStrategy.java
public Object instantiate(RootBeanDefinition bd, @Nullable String beanName, BeanFactory owner) {
    // Don't override the class with CGLIB if no overrides.
    // 如果有需要覆盖或者动态替换的方法则当然需要使用CGLIB进行动态代理,因为可以在创建代理的同时将方法织入类中
    // 但是如果没有需要动态改变的方法,为了方便直接用反射就可以了
    if (!bd.hasMethodOverrides()) {
        Constructor<?> constructorToUse;
        synchronized (bd.constructorArgumentLock) {
            // 获取缓存的构造方法或工厂方法
            constructorToUse = (Constructor<?>) bd.resolvedConstructorOrFactoryMethod;
            // 缓存为空
            if (constructorToUse == null) {
                final Class<?> clazz = bd.getBeanClass();
                // 如果clazz是接口,抛出异常
                if (clazz.isInterface()) {
                    throw new BeanInstantiationException(clazz, "Specified class is an interface");
                }
                try {
                    if (System.getSecurityManager() != null) {
                        constructorToUse = AccessController.doPrivileged(
                            (PrivilegedExceptionAction<Constructor<?>>) clazz::getDeclaredConstructor);
                    }
                    else {
                        // 获取默认的无参构造函数
                        constructorToUse = clazz.getDeclaredConstructor();
                    }
                    // 设置缓存
                    bd.resolvedConstructorOrFactoryMethod = constructorToUse;
                }
                catch (Throwable ex) {
                    throw new BeanInstantiationException(clazz, "No default constructor found", ex);
                }
            }
        }
        // 这里就是用指定的无参构造器去实例化该bean,不做具体分析了
        return BeanUtils.instantiateClass(constructorToUse);
    }
    else {
        // Must generate CGLIB subclass.
        // 用CGLIB生成子类动态织入重写的方法
        return instantiateWithMethodInjection(bd, beanName, owner);
    }
}
           

上面代码比较简单,无非就是使用默认的无参构造器去实例化

bean

,并封装成

BeanWrapper

返回。

ConstructorResolver#autowireConstructor

protected BeanWrapper autowireConstructor(
			String beanName, RootBeanDefinition mbd, @Nullable Constructor<?>[] ctors, @Nullable Object[] explicitArgs) {
	// 寻找适合的构造器,进行实例化
    return new ConstructorResolver(this).autowireConstructor(beanName, mbd, ctors, explicitArgs);
}

public BeanWrapper autowireConstructor(String beanName, RootBeanDefinition mbd,
			@Nullable Constructor<?>[] chosenCtors, @Nullable Object[] explicitArgs) {

    BeanWrapperImpl bw = new BeanWrapperImpl();
    this.beanFactory.initBeanWrapper(bw);
    // 最终实例化的构造函数
    Constructor<?> constructorToUse = null;
    // 最终用于实例化的参数Holder
    ArgumentsHolder argsHolderToUse = null;
    // 最终用于实例化的构造函数参数
    Object[] argsToUse = null;
    // 如果explicitArgs不为空,则使用explicitArgs当做构造器函数参数
    if (explicitArgs != null) {
        argsToUse = explicitArgs;
    }
    else {
        Object[] argsToResolve = null;
        synchronized (mbd.constructorArgumentLock) {
            // 获取已经缓存的构造函数或工厂方法
            constructorToUse = (Constructor<?>) mbd.resolvedConstructorOrFactoryMethod;
            if (constructorToUse != null && mbd.constructorArgumentsResolved) {
                // Found a cached constructor...
                // 获取已经缓存的构造函数参数
                argsToUse = mbd.resolvedConstructorArguments;
                if (argsToUse == null) {
                    // 如果已经缓存了构造函数或工厂方法,那么resolvedConstructorArguments和preparedConstructorArguments必定有一个缓存了构造函数参数
                    argsToResolve = mbd.preparedConstructorArguments;
                }
            }
        }
        if (argsToResolve != null) {
            // 如果argsToResolve不为空,则对构造函数参数进行解析,也就是会进行类型转换之类的操作
            // 例如 A(int,int),把配置中的 ("1","1") 转换为 (1,1)
            argsToUse = resolvePreparedArguments(beanName, mbd, bw, constructorToUse, argsToResolve, true);
        }
    }
    // 如果没有缓存构造函数或者其参数
    if (constructorToUse == null || argsToUse == null) {
        // Take specified constructors, if any.
        Constructor<?>[] candidates = chosenCtors;
        if (candidates == null) {
            Class<?> beanClass = mbd.getBeanClass();
            try {
                // 如果允许访问非public的构造函数和方法(该值默认为 true),就获取所有构造函数,否则只获取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);
            }
        }
        // 如果只有一个构造函数 && getBean()没有显示指定args && 没有定义构造函数的参数值
        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;
                }
                // 通过无参构造函数创建bean的实例,然后直接返回
                bw.setBeanInstance(instantiate(beanName, mbd, uniqueCandidate, EMPTY_ARGS));
                return bw;
            }
        }

        // Need to resolve the constructor.
        // 如果候选构造函数不为空 || 构造函数自动注入模式
        boolean autowiring = (chosenCtors != null || mbd.getResolvedAutowireMode() == AutowireCapableBeanFactory.AUTOWIRE_CONSTRUCTOR);
        ConstructorArgumentValues resolvedValues = null;

        int minNrOfArgs;
        // getBean()显示指定了参数,获取参数长度
        if (explicitArgs != null) {
            minNrOfArgs = explicitArgs.length;
        }
        else {
            // 获取定义的构造函数参数
            ConstructorArgumentValues cargs = mbd.getConstructorArgumentValues();
            resolvedValues = new ConstructorArgumentValues();
            // 解析构造函数参数并赋值到resolvedValues,返回参数个数。见下文详解
            minNrOfArgs = resolveConstructorArguments(beanName, mbd, bw, cargs, resolvedValues);
        }
        // 这里对构造函数进行排序,规则是首先是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();
            // 如果已经找到满足的构造函数 && 目标构造函数参数个数大于当前遍历的构造函数参数个数则终止
            // 因为构造函数已经是排过序的,后面不会再有更适合的了
            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 {
                    // 评估参数名称,就是判断构造函数上是否标注了@ConstructorProperties注解,如果标注了,直接取其中定义的参数名称
                    String[] paramNames = ConstructorPropertiesChecker.evaluate(candidate, parameterCount);
                    // 没有标注@ConstructorProperties注解,使用参数名称解析器,获取参数名称
                    if (paramNames == null) {
                        ParameterNameDiscoverer pnd = this.beanFactory.getParameterNameDiscoverer();
                        if (pnd != null) {
                            paramNames = pnd.getParameterNames(candidate);
                        }
                    }
                    // 创建一个参数数组以调用构造函数或工厂方法,见下文详解
                    // 主要是通过参数类型和参数名解析构造函数或工厂方法所需的参数(如果参数是其他bean,则会解析依赖的bean)
                    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;
                }
            }
            // resolvedValues为空, explicitArgs不为空,即显示指定了getBean()的args参数
            else {
                // Explicit arguments given -> arguments length must match exactly.
                // 如果当前构造函数参数个数不等的explicitArgs的长度,直接跳过该构造函数
                if (parameterCount != explicitArgs.length) {
                    continue;
                }
                // 把explicitArgs封装进ArgumentsHolder
                argsHolder = new ArgumentsHolder(explicitArgs);
            }
            // 根据mbd的解析构造函数模式(true: 宽松模式,false:严格模式)
            // 将argsHolder的参数和paramTypes进行比较,计算paramTypes的类型差异权重值
            int typeDiffWeight = (mbd.isLenientConstructorResolution() ?
                                  argsHolder.getTypeDifferenceWeight(paramTypes) : argsHolder.getAssignabilityWeight(paramTypes));
            // Choose this constructor if it represents the closest match.
            // 差异值越小代表构造函数越匹配,则选择此构造函数
            if (typeDiffWeight < minTypeDiffWeight) {
                constructorToUse = candidate;
                argsHolderToUse = argsHolder;
                argsToUse = argsHolder.arguments;
                minTypeDiffWeight = typeDiffWeight;
                // 如果出现权重值更小的候选者,则将ambiguousConstructors清空,允许之前存在权重值相同的候选者
                ambiguousConstructors = null;
            }
            // 两个候选者权重值相同,并且是当前遍历过权重值最小的
            else if (constructorToUse != null && typeDiffWeight == minTypeDiffWeight) {
                // 将两个候选者添加到ambiguousConstructors
                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);
        }
        // getBean()方法没有指定args参数 && 构造函数参数不为空
        if (explicitArgs == null && argsHolderToUse != null) {
            // 缓存解析过后的构造函数和参数
            argsHolderToUse.storeCache(mbd, constructorToUse);
        }
    }

    Assert.state(argsToUse != null, "Unresolved constructor arguments");
    // 利用反射创建bean实例
    bw.setBeanInstance(instantiate(beanName, mbd, constructorToUse, argsToUse));
    return bw;
}
           

上面代码的功能主要如下:

  1. 构造函数参数的确定
    • 如果

      explicitArgs

      参数不为空,那就可以直接确定参数。因为

      explicitArgs

      参数是在调用

      getBean()

      时手动指定的,这个主要用于静态工厂方法的调用。
    • 缓存中不为空,那么可以直接拿过来使用。
    • BeanDefinition

      中读取,我们所定义的

      bean

      都会生成一个

      BeanDefinition

      ,其中记录了定义了构造函数参数通过

      getConstructorArgumentValues()

      获取。
  2. 构造函数的确定。经过第一步已经确定构造函数的参数,接下来就是用参数个数在所有的构造函数中锁定对应的构造函数。匹配之前会对构造函数进行排序,首先是

    public

    构造函数且参数个数从多到少,然后是非

    public

    构造函数且参数个数有多到少。这样可以迅速判断排在后面的构造函数参数个数是否符合条件。
  3. 根据对应的构造函数转换对应的参数类型。
  4. 根据实例化策略以及得到的构造函数和构造函数参数实例化

    bean

ConstructorResolver#resolveConstructorArguments

private int resolveConstructorArguments(String beanName, RootBeanDefinition mbd, BeanWrapper bw,
			ConstructorArgumentValues cargs, ConstructorArgumentValues resolvedValues) {
    // 获取自定义类型转换器
    TypeConverter customConverter = this.beanFactory.getCustomTypeConverter();
    TypeConverter converter = (customConverter != null ? customConverter : bw); 
    // 如果没有自定义的转换器就用bw
    BeanDefinitionValueResolver valueResolver =
        new BeanDefinitionValueResolver(this.beanFactory, beanName, mbd, converter);
    // minNrOfArgs初始化为indexedArgumentValues+genericArgumentValues的个数总和
    int minNrOfArgs = cargs.getArgumentCount();
    // 遍历IndexArgumentValues,这里的IndexArgumentValues就带下标的,如:<constructor-arg index="0" value="1"/>
    for (Map.Entry<Integer, ConstructorArgumentValues.ValueHolder> entry : cargs.getIndexedArgumentValues().entrySet()) {
        int index = entry.getKey();
        if (index < 0) {
            throw new BeanCreationException(mbd.getResourceDescription(), beanName,
                                            "Invalid constructor argument index: " + index);
        } 
        // 如果index大于minNrOfArgs,修改minNrOfArgs值
        if (index > minNrOfArgs) {
            // 因为index是构造函数下标值,所以总数这边要加1
            minNrOfArgs = index + 1; 
        }
        ConstructorArgumentValues.ValueHolder valueHolder = entry.getValue();
        // 如果参数类型已经转换过,直接添加进resolvedValues
        if (valueHolder.isConverted()) { 
            resolvedValues.addIndexedArgumentValue(index, valueHolder);
        }
        // 参数类型没有转换过,进行转换
        else { 
            Object resolvedValue =
                valueResolver.resolveValueIfNecessary("constructor argument", valueHolder.getValue());
            // 使用转换过的参数值构建ValueHolder
            ConstructorArgumentValues.ValueHolder resolvedValueHolder = 
						new ConstructorArgumentValues.ValueHolder(resolvedValue, valueHolder.getType(), valueHolder.getName());
            resolvedValueHolder.setSource(valueHolder); 
            // 添加进resolvedValues
            resolvedValues.addIndexedArgumentValue(index, resolvedValueHolder);
        }
    }
    // 遍历GenericArgumentValues并进行类型转换和上面一样,这里的GenericArgumentValues就是没有指定下标的,如:<constructor-arg value="1"/>
    for (ConstructorArgumentValues.ValueHolder valueHolder : cargs.getGenericArgumentValues()) {
        if (valueHolder.isConverted()) {
            resolvedValues.addGenericArgumentValue(valueHolder);
        }
        else {
            Object resolvedValue =
                valueResolver.resolveValueIfNecessary("constructor argument", valueHolder.getValue());
            ConstructorArgumentValues.ValueHolder resolvedValueHolder = new ConstructorArgumentValues.ValueHolder(
                resolvedValue, valueHolder.getType(), valueHolder.getName());
            resolvedValueHolder.setSource(valueHolder);
            resolvedValues.addGenericArgumentValue(resolvedValueHolder);
        }
    }
    // 返回参数个数
    return minNrOfArgs;
}
           

上面代码主要将

indexedArgumentValues

genericArgumentValues

的值调用

resolveValueIfNecessary()

进行解析;

resolveValueIfNecessary()

主要解析参数的类型,比如

ref

属性引用的

beanName

会通过

getBean()

返回实例。

ConstructorResolver#createArgumentArray

private ArgumentsHolder createArgumentArray(
    String beanName, RootBeanDefinition mbd, @Nullable ConstructorArgumentValues resolvedValues,BeanWrapper bw, Class<?>[] paramTypes, @Nullable String[] paramNames, Executable executable,boolean autowiring, boolean fallback) throws UnsatisfiedDependencyException {
    // 获取类型转换器
    TypeConverter customConverter = this.beanFactory.getCustomTypeConverter();
    TypeConverter converter = (customConverter != null ? customConverter : bw);
    // 构建ArgumentsHolder
    ArgumentsHolder args = new ArgumentsHolder(paramTypes.length);
    Set<ConstructorArgumentValues.ValueHolder> usedValueHolders = new HashSet<>(paramTypes.length);
    Set<String> autowiredBeanNames = new LinkedHashSet<>(4);
    // 遍历参数类型数组
    for (int paramIndex = 0; paramIndex < paramTypes.length; paramIndex++) {
        // 获取参数类型和名称
        Class<?> paramType = paramTypes[paramIndex]; 
        String paramName = (paramNames != null ? paramNames[paramIndex] : "");
        // Try to find matching constructor argument value, either indexed or generic.
        ConstructorArgumentValues.ValueHolder valueHolder = null;
        if (resolvedValues != null) {
            // 根据参数的下标、类型、名称查询是否有匹配的
            valueHolder = resolvedValues.getArgumentValue(paramIndex, paramType, paramName, usedValueHolders);
            // If we couldn't find a direct match and are not supposed to autowire,
            // let's try the next generic, untyped argument value as fallback:
            // it could match after type conversion (for example, String -> int).
            // 没有匹配的 && 不是自动装配。尝试下一个通用的无类型参数值作为降级方法,它可以在类型转换后匹配 (例如,String -> int)
            if (valueHolder == null && (!autowiring || paramTypes.length == resolvedValues.getArgumentCount())) {
                valueHolder = resolvedValues.getGenericArgumentValue(null, null, usedValueHolders);
            }
        }
        // 找到了匹配的valueHolder
        if (valueHolder != null) {
            // We found a potential match - let's give it a try.
            // Do not consider the same value definition multiple times!
            // 添加进usedValueHolders
            usedValueHolders.add(valueHolder);
            Object originalValue = valueHolder.getValue();
            Object convertedValue;
            // 类型已经转换过
            if (valueHolder.isConverted()) {
                // 获取已经转换过的值,作为args在paramIndex的预备参数
                convertedValue = valueHolder.getConvertedValue();
                args.preparedArguments[paramIndex] = convertedValue;
            }
            // 类型没有转换过
            else {
                // 将构造方法和参数下标封装成MethodParameter(MethodParameter是封装方法和参数索引的工具类)
                MethodParameter methodParam = MethodParameter.forExecutable(executable, paramIndex);
                try {
                    // 将原始值转换为paramType类型的值,无法转换时抛出异常
                    convertedValue = converter.convertIfNecessary(originalValue, paramType, methodParam);
                }
                catch (TypeMismatchException ex) {
                    throw new UnsatisfiedDependencyException(
                        mbd.getResourceDescription(), beanName, new InjectionPoint(methodParam),
                        "Could not convert argument value of type [" +
										ObjectUtils.nullSafeClassName(valueHolder.getValue()) +
										"] to required type [" + paramType.getName() + "]: " + ex.getMessage());
                }
                Object sourceHolder = valueHolder.getSource();
                if (sourceHolder instanceof ConstructorArgumentValues.ValueHolder) {
                    Object sourceValue = ((ConstructorArgumentValues.ValueHolder) sourceHolder).getValue();
                    // 标记args需要解析
                    args.resolveNecessary = true;
                    // 将sourceValue作为args在paramIndex位置的预备参数
                    args.preparedArguments[paramIndex] = sourceValue;
                }
            }
            // 将convertedValue作为args在paramIndex位置的参数
            args.arguments[paramIndex] = convertedValue;
            //  将originalValue作为args在paramIndex位置的原始参数
            args.rawArguments[paramIndex] = originalValue;
        }
        // 没有找到匹配的valueHolder
        else {
            // 将构造方法和参数下标封装成MethodParameter
            MethodParameter methodParam = MethodParameter.forExecutable(executable, paramIndex);
            // No explicit match found: we're either supposed to autowire or
            // have to fail creating an argument array for the given constructor.
            // 找不到明确的匹配,并且不是自动注入,抛出异常
            if (!autowiring) {
                throw new UnsatisfiedDependencyException(
							mbd.getResourceDescription(), beanName, new InjectionPoint(methodParam),
                    "Ambiguous argument values for parameter of type [" + paramType.getName() +
                    "] - did you specify the correct bean references as arguments?");
            }
            try {
                // 如果是自动注入,用resolveAutowiredArgument()解析参数,见下文详解
                // 构造函数自动注入中的参数bean就是在这边处理
                Object autowiredArgument = resolveAutowiredArgument(
                    methodParam, beanName, autowiredBeanNames, converter, fallback);
                // 将通过自动装配解析出来的参数赋值给args
                args.rawArguments[paramIndex] = autowiredArgument;
                args.arguments[paramIndex] = autowiredArgument;
                args.preparedArguments[paramIndex] = autowiredArgumentMarker;
                args.resolveNecessary = true;
            }
            catch (BeansException ex) {
                throw new UnsatisfiedDependencyException(
                    mbd.getResourceDescription(), beanName, new InjectionPoint(methodParam), ex);
            }
        }
    }
    // 如果依赖了其他的bean,则注册依赖关系(这边的autowiredBeanNames,就是所有依赖的beanName)
    for (String autowiredBeanName : autowiredBeanNames) {
        this.beanFactory.registerDependentBean(autowiredBeanName, beanName);
        if (logger.isDebugEnabled()) {
            logger.debug("Autowiring by type from bean name '" + beanName +
                         "' via " + (executable instanceof Constructor ? "constructor" : "factory method") +
                         " to bean named '" + autowiredBeanName + "'");
        }
    }
	// 返回解析后的参数值
    return args;
}
           

上面代码判断构造函数如果有匹配的参数会转换成对应类型,如果没有匹配的参数,多半是构造函数自动注入,通过

resolveAutowiredArgument()

去查找

bean

并返回实例。

ConstructorResolver#resolveAutowiredArgument

protected Object resolveAutowiredArgument(MethodParameter param, String beanName,
                                          @Nullable Set<String> autowiredBeanNames, TypeConverter typeConverter, boolean fallback) {
    // 获取参数的类型
    Class<?> paramType = param.getParameterType();
    // 如果参数类型是InjectionPoint
    if (InjectionPoint.class.isAssignableFrom(paramType)) {
        // 拿到当前的InjectionPoint(存储了当前正在解析依赖的方法参数信息,DependencyDescriptor)
        InjectionPoint injectionPoint = currentInjectionPoint.get();
        if (injectionPoint == null) {
            // 当前injectionPoint为空,则抛出异常:目前没有可用的InjectionPoint
            throw new IllegalStateException("No current InjectionPoint available for " + param);
        }
        // 当前injectionPoint不为空,直接返回
        return injectionPoint;
    }
    try {
        // 解析指定依赖,DependencyDescriptor:将MethodParameter的方法参数索引信息封装成DependencyDescriptor,见下文详解
        return this.beanFactory.resolveDependency(
					new DependencyDescriptor(param, true), beanName, autowiredBeanNames, typeConverter);
    }
    catch (NoUniqueBeanDefinitionException ex) {
        throw ex;
    }
    catch (NoSuchBeanDefinitionException ex) {
        if (fallback) {
            // Single constructor or factory method -> let's return an empty array/collection
            // for e.g. a vararg or a non-null List/Set/Map parameter.
            if (paramType.isArray()) {
                return Array.newInstance(paramType.getComponentType(), 0);
            }
            else if (CollectionFactory.isApproximableCollectionType(paramType)) {
                return CollectionFactory.createCollection(paramType, 0);
            }
            else if (CollectionFactory.isApproximableMapType(paramType)) {
                return CollectionFactory.createMap(paramType, 0);
            }
        }
        throw ex;
    }
}
           

上面代码我们一般只需要重点关注

this.beanFactory.resolveDependency()

这个方法,这个就是解决依赖注入的秘密所在。

DefaultListableBeanFactory#resolveDependency

public Object resolveDependency(DependencyDescriptor descriptor, @Nullable String requestingBeanName,
                                @Nullable Set<String> autowiredBeanNames, @Nullable TypeConverter typeConverter) throws BeansException {

    descriptor.initParameterNameDiscovery(getParameterNameDiscoverer());
    // Optional类型的处理,说明Spring也可以注入Optional类型的参数
    if (Optional.class == descriptor.getDependencyType()) {
        return createOptionalDependency(descriptor, requestingBeanName);
    }
    // ObjectFactory或ObjectProvider类型的处理
    else if (ObjectFactory.class == descriptor.getDependencyType() ||
             ObjectProvider.class == descriptor.getDependencyType()) {
        return new DependencyObjectProvider(descriptor, requestingBeanName);
    }
    // javax.inject.Provider类型的处理
    else if (javaxInjectProviderClass == descriptor.getDependencyType()) {
        return new Jsr330Factory().createDependencyProvider(descriptor, requestingBeanName);
    }
    else {
        // 获取延迟解析代理
        Object result = getAutowireCandidateResolver().getLazyResolutionProxyIfNecessary(
					descriptor, requestingBeanName);
        if (result == null) {
            // 解析依赖,返回的result为最终需要注入的bean实例,见下文详解
            result = doResolveDependency(descriptor, requestingBeanName, autowiredBeanNames, typeConverter);
        }
        return result;
    }
}
           

上面代码主要判断如果需要注入的

bean

的类型是

Optional

ObjectFactory

ObjectProvider

Provider

会做特殊的处理,一般情况下注入的

bean

会走最后的

doResolveDependency()

。 还有一个比较重要的参数

DependencyDescriptor

,这个类就是依赖描述符,存储了需要注入

bean

的类型、构造器参数的下标(构造器注入该值不为空)、是否必需、字段名称(字段注入该值不为空)、方法名称(

setter

方法注入该值不为空)等。

DefaultListableBeanFactory#doResolveDependency

public Object doResolveDependency(DependencyDescriptor descriptor, @Nullable String beanName,@Nullable Set<String> autowiredBeanNames, @Nullable TypeConverter typeConverter) throws BeansException {

    InjectionPoint previousInjectionPoint = ConstructorResolver.setCurrentInjectionPoint(descriptor);
    try {
        // 获取需要注入bean的快捷方式,不为空直接返回
        Object shortcut = descriptor.resolveShortcut(this);
        if (shortcut != null) {
            return shortcut;
        }
        // 获取需要注入bean的类型
        Class<?> type = descriptor.getDependencyType();
        // 用于支持Spring中新增的注解@Value(确定给定的依赖项是否声明@Value注解,如果有则拿到值)
        Object value = getAutowireCandidateResolver().getSuggestedValue(descriptor);
        if (value != null) {
            if (value instanceof String) {
                String strVal = resolveEmbeddedValue((String) value);
                BeanDefinition bd = (beanName != null && containsBean(beanName) ?
                                     getMergedBeanDefinition(beanName) : null);
                value = evaluateBeanDefinitionString(strVal, bd);
            }
            TypeConverter converter = (typeConverter != null ? typeConverter : getTypeConverter());
            try {
                return converter.convertIfNecessary(value, type, descriptor.getTypeDescriptor());
            }
            catch (UnsupportedOperationException ex) {
                // A custom TypeConverter which does not support TypeDescriptor resolution...
                return (descriptor.getField() != null ?
                        converter.convertIfNecessary(value, type, descriptor.getField()) :converter.convertIfNecessary(value, type, descriptor.getMethodParameter()));
            }
        }
        // 解析MultipleBean,例如 Array,Collection,Map
        Object multipleBeans = resolveMultipleBeans(descriptor, beanName, autowiredBeanNames, typeConverter);
        if (multipleBeans != null) {
            return multipleBeans;
        }
        // 根据类型找到匹配的bean,matchingBeans(key: beanName value: 如果bean已经缓存了实例(例如单例bean会缓存其实例),
        // 就是bean的实例,否则就是对应的class对象)
        Map<String, Object> matchingBeans = findAutowireCandidates(beanName, type, descriptor);
        if (matchingBeans.isEmpty()) {
            // 没有找到匹配的bean,判断是不是必需的,不是直接返回null,否则抛出异常
            if (isRequired(descriptor)) {
                raiseNoMatchingBeanFound(type, descriptor.getResolvableType(), descriptor);
            }
            return null;
        }

        String autowiredBeanName;
        Object instanceCandidate;
        // 如果有多个匹配的候选者
        if (matchingBeans.size() > 1) {
            // 判断最佳的候选者,也就是寻找最匹配的beanName
            autowiredBeanName = determineAutowireCandidate(matchingBeans, descriptor);
            if (autowiredBeanName == null) {
                if (isRequired(descriptor) || !indicatesMultipleBeans(type)) {
                    return descriptor.resolveNotUnique(descriptor.getResolvableType(), matchingBeans);
                }
                else {
                    // In case of an optional Collection/Map, silently ignore a non-unique case:
                    // possibly it was meant to be an empty collection of multiple regular beans
                    // (before 4.3 in particular when we didn't even look for collection beans).
                    return null;
                }
            }
            // 拿到autowiredBeanName对应的value(bean实例或bean实例类型)
            instanceCandidate = matchingBeans.get(autowiredBeanName);
        }
        else {
            // We have exactly one match.
            // 只找到一个符合的bean
            Map.Entry<String, Object> entry = matchingBeans.entrySet().iterator().next();
            autowiredBeanName = entry.getKey();
            instanceCandidate = entry.getValue();
        }

        if (autowiredBeanNames != null) {
            // 将依赖的beanName添加到autowiredBeanNames中
            autowiredBeanNames.add(autowiredBeanName);
        }
        // 如果需要注入的bean没有缓存实例,那么instanceCandidate是一个Class对象,再根据getBean()去获取对应的实例
        if (instanceCandidate instanceof Class) {
            instanceCandidate = descriptor.resolveCandidate(autowiredBeanName, type, this);
        }
        Object result = instanceCandidate;
        if (result instanceof NullBean) {
            if (isRequired(descriptor)) {
                raiseNoMatchingBeanFound(type, descriptor.getResolvableType(), descriptor);
            }
            result = null;
        }
        if (!ClassUtils.isAssignableValue(type, result)) {
            throw new BeanNotOfRequiredTypeException(autowiredBeanName, type, instanceCandidate.getClass());
        }
        // 返回最终需要注入的bean实例
        return result;
    }
    finally {
        ConstructorResolver.setCurrentInjectionPoint(previousInjectionPoint);
    }
}
           

上面代码才是真正去获取需要注入的

bean

,大概分为以下几个步骤:

  1. 查看是否有快捷方式获取注入

    bean

    是否为空,不为空直接返回。这里的快捷方式是通过继承

    DependencyDescriptor

    并重写

    resolveShortcut()

    来实现。
  2. 如果参数使用

    @Value

    注解修饰了,如果获取到值直接返回。
  3. 解析

    MultipleBean

    ,这里的

    MultipleBean

    一般是

    Array

    Collection

    Map

    这种,不为空直接返回。
  4. 根据类型找到所有匹配的

    bean

    matchingBeans

    key

    beanName

    value

    的值有两种情况,如果bean已经缓存了实例(例如单例bean会缓存其实例),就是bean的实例,否则就是对应的class对象)。
  5. matchingBeans

    为空,判断需要注入的

    bean

    是否是必须的,如果是抛出异常,否则返回

    null

  6. matchingBeans

    长度大于1,代表有多个候选者;选择最佳的候选者,规则是:
    1. 首先查找

      primary

      属性为

      true

      的。
    2. 查找优先级最高的,实现

      PriorityOrdered

      接口或者标注

      @Priority

      注解的。
    3. 查找名称匹配的。
  7. 只有一个候选者,直接使用。
  8. 如果需要注入的

    bean

    没有缓存实例,那么

    instanceCandidate

    是一个

    Class

    对象,再根据

    getBean()

    去获取对应的实例。
  9. 最终返回需要注入的

    bean

    实例。

AbstractAutowireCapableBeanFactory#applyMergedBeanDefinitionPostProcessors

protected void applyMergedBeanDefinitionPostProcessors(RootBeanDefinition mbd, Class<?> beanType, String beanName) {
    for (BeanPostProcessor bp : getBeanPostProcessors()) {
        if (bp instanceof MergedBeanDefinitionPostProcessor) {
            MergedBeanDefinitionPostProcessor bdp = (MergedBeanDefinitionPostProcessor) bp;
            bdp.postProcessMergedBeanDefinition(mbd, beanType, beanName);
        }
    }
}
           

上面代码很简单,无非就是拿到所有注册的

BeanPostProcessor

,然后遍历判断是否是

MeragedBeanDefinitionPostProcessor

类型,是的话进行

BeanDefinition

合并后的方法回调,在这个回调方法内你可以对指定

bean

BeanDefinition

做一些修改。

下面我们简单看一下

MergedBeanDefinitionPostProcessor

接口中的方法:

public interface MergedBeanDefinitionPostProcessor extends BeanPostProcessor {

    /**
    * 对指定bean的BeanDefinition合并后的处理方法回调
    */
    void postProcessMergedBeanDefinition(RootBeanDefinition beanDefinition, Class<?> beanType, String beanName);

    /**
    * 通知已重新设置指定beanName的BeanDefinition,如果实现该方法应该清除受影响的bean的所有元数据
    * @since 5.1
    */
    default void resetBeanDefinition(String beanName) {
        
    }

}
           

DefaultSingletonBeanRegistry#addSingletonFactory

protected void addSingletonFactory(String beanName, ObjectFactory<?> singletonFactory) {
    Assert.notNull(singletonFactory, "Singleton factory must not be null");
    // 加锁
    synchronized (this.singletonObjects) {
        // 如果单例bean缓存中不包含当前beanName
        if (!this.singletonObjects.containsKey(beanName)) {
            // 将创建实例的ObjectFactory加入到缓存中
            this.singletonFactories.put(beanName, singletonFactory);
            // 将bean从早起单例bean缓存中移除
            this.earlySingletonObjects.remove(beanName);
            // 将beanName加入到已经注册过的单例bean缓存中
            this.registeredSingletons.add(beanName); 
        }
    }
}
           

上面代码将

ObjectFactory

加入

singletonFactories

缓存中,以下是

singletonFactories

的声明:

/** Cache of singleton factories: bean name to ObjectFactory. */
private final Map<String, ObjectFactory<?>> singletonFactories = new HashMap<>(16);
           

下面以一个简单的AB循环依赖为例,类A中含有属性类B,而类B中又会含有属性类A。那么初始化 beanA 的过程如下图所示:

Spring IoC createBean 方法详解

Spring 解决循环依赖的方法就在

addSingletonFactory()

getBean()

方法中。首先创建

beanA

时,将实例化好的

beanA

封装成

ObjectFactory

放入

singletonFactories

缓存中,接着进行属性填充;因为依赖

beanB

所以先去实例化

beanB

,接着

beanB

属性填充,发现需要

beanA

就调用

getBean()

去获取

beanA

实例。上篇文章讲过

getBean()

会首先判断缓存中是否有已经创建好的

bean

或者是

beanFactory

,如下代码所示:

protected Object getSingleton(String beanName, boolean allowEarlyReference) {
    // 检查单例传中是否存在
    Object singletonObject = this.singletonObjects.get(beanName);
    if (singletonObject == null && isSingletonCurrentlyInCreation(beanName)) {
        // 如果为空,并且当前bean正在创建中,锁定全局变量进行处理
        synchronized (this.singletonObjects) {
            singletonObject = this.earlySingletonObjects.get(beanName);
            if (singletonObject == null && allowEarlyReference) {
                // 当某些方法需要提前初始化时则会调用addSingletonFactory方法将对应的
                ObjectFactory<?> singletonFactory = this.singletonFactories.get(beanName);
                if (singletonFactory != null) {
                    // 调用预先设定的getObject(),此时就会返回未填充属性的beanA
                    singletonObject = singletonFactory.getObject();
                    this.earlySingletonObjects.put(beanName, singletonObject);
                    this.singletonFactories.remove(beanName);
                }
            }
        }
    }
    return singletonObject;
}
           

因为

beanA

beanB

中的

beanA

所表示的属性地址是一样的,所以在

beanA

中创建好的属性填充自然可以通过

beanB

中的

beanA

获取,这样就解决了循环依赖的问题。

AbstractAutowireCapableBeanFactory#getEarlyBeanReference

protected Object getEarlyBeanReference(String beanName, RootBeanDefinition mbd, Object bean) {
    Object exposedObject = bean;
    if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
        for (BeanPostProcessor bp : getBeanPostProcessors()) {
            if (bp instanceof SmartInstantiationAwareBeanPostProcessor) {
                SmartInstantiationAwareBeanPostProcessor ibp = (SmartInstantiationAwareBeanPostProcessor) bp;
                exposedObject = ibp.getEarlyBeanReference(exposedObject, beanName);
            }
        }
    }
    return exposedObject;
}
           

上面代码很简单,就是判断是否有注册

InstantiationAwareBeanPostProcessor

的实现,如果有遍历找到类型是

SmartInstantiationAwareBeanPostProcessor

调用

getEarlyBeanReference()

返回

bean

的实例。

这里又是一个 Spring 的扩展点,其中我们熟知的 AOP 就是在这里将

advice

动态织入

bean

中,若没有则直接返回

bean

,不做任何处理。

AbstractAutowireCapableBeanFactory#populateBean

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

    // 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
    // 例如:可以用来支持属性注入的类型
    if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
        for (BeanPostProcessor bp : getBeanPostProcessors()) {
            if (bp instanceof InstantiationAwareBeanPostProcessor) {
                // 这里会调用bean实例化后的生命周期回调,返回false会跳过下面的属性赋值阶段
                InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
                if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {
                    return;
                }
            }
        }
    }
    // 获取PropertyValues
    PropertyValues pvs = (mbd.hasPropertyValues() ? mbd.getPropertyValues() : null);

    int resolvedAutowireMode = mbd.getResolvedAutowireMode();
    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;
    }

    // 是否有注册InstantiationAwareBeanPostProcessors的实现类
    boolean hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors();
    boolean needsDepCheck = (mbd.getDependencyCheck() != AbstractBeanDefinition.DEPENDENCY_CHECK_NONE);

    PropertyDescriptor[] filteredPds = null;
    if (hasInstAwareBpps) {
        if (pvs == null) {
            pvs = mbd.getPropertyValues();
        }
        // 遍历并找到InstantiationAwareBeanPostProcessor的实现类,调用处理属性值的后置处理方法
        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);
                    }
                    pvsToUse = ibp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName);
                    // 如果属性值的后置处理方法返回null,直接返回,不会进行底下的属性值应用阶段
                    if (pvsToUse == null) {
                        return;
                    }
                }
                pvs = pvsToUse;
            }
        }
    }
    if (needsDepCheck) {
        if (filteredPds == null) {
            filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
        }
        checkDependencies(beanName, mbd, filteredPds, pvs);
    }

    if (pvs != null) {
        // 属性填充,见下文详解
        applyPropertyValues(beanName, mbd, bw, pvs);
    }
}
           

上面代码首先会调用

bean

的实例化后生命周期回调方法,如果返回

false

会跳过下面的属性赋值阶段。下面我们简单看一下

InstantiationAwareBeanPostProcessors

的接口定义:

public interface InstantiationAwareBeanPostProcessor extends BeanPostProcessor {

	/**
	 * Bean 实例化前调用,返回非 {@code null} IoC 容器不会对 Bean 进行实例化 并且后续的生命周期回调方	  *	法不会调用,返回 {@code null} 则进行 IoC 容器对 Bean 的实例化
	 * 该方法上篇文章分析过
	 */
	@Nullable
	default Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) throws BeansException {
		return null;
	}

	/**
	 * Bean 实例化之后,属性填充之前调用,返回 {@code true} 则进行默认的属性填充步骤,返回 {@code 		 * false} 会跳过属性填充阶段。
	 */
	default boolean postProcessAfterInstantiation(Object bean, String beanName) throws BeansException {
		return true;
	}

	/**
	 * Bean 实例化后属性赋值前调用,PropertyValues 是已经封装好的设置的属性值,返回 {@code null} 继续
	 * 使用现有属性,否则会替换 PropertyValues。
	 * @since 5.1版本新加的和底下的方法一样
	 */
	@Nullable
	default PropertyValues postProcessProperties(PropertyValues pvs, Object bean, String beanName)
			throws BeansException {
		return null;
	}

	/**
	 * 跟上面方法一样的功能,只不过是5.1以前版本所使用的
	 * 返回 {@code null} 会跳过属性填充阶段
	 */
	@Deprecated
	@Nullable
	default PropertyValues postProcessPropertyValues(
			PropertyValues pvs, PropertyDescriptor[] pds, Object bean, String beanName) throws BeansException {

		return pvs;
	}

}
           

接着判断是否是按 名称 或者 类型 自动注入属性并填入

newPvs

中,接着调用

bean

属性填充前的生命周期回调。属性填充前生命周期回调方法有两个

postProcessProperties()

postProcessPropertyValues()

,第一个是 Spring 5.1 新加的,后面的是老的,已经被标记为过时;首先会调用

postProcessProperties()

如果返回空调用

postProcessPropertyValues()

,否则直接使用返回的

PropertyValues

postProcessPropertyValues()

如果返回空会直接跳过属性填充阶段,不为空直接使用返回的

PropertyValues

AbstractAutowireCapableBeanFactory#autowireByName

protected void autowireByName(
    String beanName, AbstractBeanDefinition mbd, BeanWrapper bw, MutablePropertyValues pvs) {
    // 寻找bw中需要依赖注入的属性名称
    String[] propertyNames = unsatisfiedNonSimpleProperties(mbd, bw);
    // 遍历需要注入的bean
    for (String propertyName : propertyNames) {
        if (containsBean(propertyName)) {
            Object bean = getBean(propertyName);
            // 将需要注入bean的实例加入到pvs
            pvs.add(propertyName, bean);
            // 注册依赖关系,上篇文章有分析过
            registerDependentBean(propertyName, beanName);
            if (logger.isTraceEnabled()) {
                logger.trace("Added autowiring by name from bean name '" + beanName +
                             "' via property '" + propertyName + "' to bean named '" + propertyName + "'");
            }
        } else {
            // 当前需要注入的bean,抛出异常
            if (logger.isTraceEnabled()) {
                logger.trace("Not autowiring property '" + propertyName + "' of bean '" + beanName + "' by name: no matching bean found");
            }
        }
    }
}
           

AbstractAutowireCapableBeanFactory#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<>(4);
    // 寻找bw中需要依赖注入的属性名称
    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()) {
                // 获取属性的可写方法,一般是set方法
                MethodParameter methodParam = BeanUtils.getWriteMethodParameter(pd);
                // Do not allow eager init for type matching in case of a prioritized post-processor.
                boolean eager = !(bw.getWrappedInstance() instanceof PriorityOrdered);
                DependencyDescriptor desc = new AutowireByTypeDependencyDescriptor(methodParam, eager);
                // 这个方法上面分析过,这里不再赘述,最后返回符合条件需要注入的bean实例
                Object autowiredArgument = resolveDependency(desc, beanName, autowiredBeanNames, converter);
                if (autowiredArgument != null) {
                    // 需要注入的bean实例不为空,加入到pvc
                    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);
        }
    }
}
           

AbstractAutowireCapableBeanFactory#applyPropertyValues

protected void applyPropertyValues(String beanName, BeanDefinition mbd, BeanWrapper bw, PropertyValues pvs) {
    // 属性为空,直接返回
    if (pvs.isEmpty()) {
        return;
    }

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

    MutablePropertyValues mpvs = null;
    List<PropertyValue> original;

    if (pvs instanceof MutablePropertyValues) {
        mpvs = (MutablePropertyValues) pvs;
        // 快捷方式,如果属性已经转换过,直接填充进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 {
        // 获取属性列表
        original = Arrays.asList(pvs.getPropertyValues());
    }

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

    // Create a deep copy, resolving any references for values.
    // 创建深拷贝,解决引用的问题
    List<PropertyValue> deepCopy = new ArrayList<>(original.size());
    boolean resolveNecessary = false;
    // 遍历属性,将属性转换为对应的类型
    for (PropertyValue pv : original) {
        // 如果pv类型转换过,直接添加进deepCopy
        if (pv.isConverted()) {
            deepCopy.add(pv);
        } else {
            // 进行转换
            // 拿到pv原始属性名和属性值
            String propertyName = pv.getName();
            Object originalValue = pv.getValue();
            if (originalValue == AutowiredPropertyMarker.INSTANCE) {
                Method writeMethod = bw.getPropertyDescriptor(propertyName).getWriteMethod();
                if (writeMethod == null) {
                    throw new IllegalArgumentException("Autowire marker for property without write method: " + pv);
                }
                originalValue = new DependencyDescriptor(new MethodParameter(writeMethod, 0), true);
            }
            // 进行类型转换
            Object resolvedValue = valueResolver.resolveValueIfNecessary(pv, originalValue);
            Object convertedValue = resolvedValue;
            boolean convertible = bw.isWritableProperty(propertyName) &&
                !PropertyAccessorUtils.isNestedOrIndexedProperty(propertyName);
            if (convertible) {
                // 如果可转换,则转换指定目标属性的给定值
                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.
            // 在合并的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 {
        // 填充bean属性值
        bw.setPropertyValues(new MutablePropertyValues(deepCopy));
    } catch (BeansException ex) {
        throw new BeanCreationException(
					mbd.getResourceDescription(), beanName, "Error setting property values", ex);
    }
}
           

上面代码主要就是进行属性的类型转换,最后填充

bean

的属性值,这里一般就是利用反射使用

set()

去给属性赋值。

AbstractAutoCapableBeanFactory#initializeBean

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 {
       // BeanAware的接口回调,见下文详解
       invokeAwareMethods(beanName, bean);
   }

   Object wrappedBean = bean;
   if (mbd == null || !mbd.isSynthetic()) {
       // BeanPostProcessor的postProcessBeforeInitialization()回调,也就是bean初始化前的回调
       // 在 ApplicationContextAwareProcessor实现的postProcessBeforeInitialization方法中会执行
       // ApplicationContext Aware的接口回调。
       // InitDestoryAnnotationBeanPostProcessor的postProcessBeforeInitialization()中会执行
       // 标注了@PostConstruct注解的方法。
       wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
   }

   try {
       // 调用bean的自定义初始化方法,如afterPropertiesSet,XML中的init属性指定的方法等
       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()回调,也就是bean初始化后的回调
       wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
   }

   return wrappedBean;
}
           

AbstractAutowireCapableBeanFactory#invokeAwareMethods

private void invokeAwareMethods(final String beanName, final Object bean) {
    if (bean instanceof Aware) {
        // BeanNameAware接口方法回调
        if (bean instanceof BeanNameAware) {
            ((BeanNameAware) bean).setBeanName(beanName);
        }
        // BeanClassLoaderAware接口方法回调
        if (bean instanceof BeanClassLoaderAware) {
            ClassLoader bcl = getBeanClassLoader();
            if (bcl != null) {
                ((BeanClassLoaderAware) bean).setBeanClassLoader(bcl);
            }
        }
        // BeanFactoryAware接口方法回调
        if (bean instanceof BeanFactoryAware) {
            ((BeanFactoryAware)
             bean).setBeanFactory(AbstractAutowireCapableBeanFactory.this);
        }
    }
}
           

实现这些

Aware

接口的

bean

的被初始化之前,可以取得一些相对应的资源,比如

beanName

beanFactory

等。

AbstractAutowireCapableBeanFactory#applyBeanPostProcessorsBeforeInitialization

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

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

AbstractAutowireCapableBeanFactory#invokeInitMethods

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

    // bean是否实现InitializingBean接口
    boolean isInitializingBean = (bean instanceof InitializingBean);
    if (isInitializingBean && (mbd == null || !mbd.isExternallyManagedInitMethod("afterPropertiesSet"))) {
        if (logger.isTraceEnabled()) {
            logger.trace("Invoking afterPropertiesSet() on bean with name '" + beanName + "'");
        }
        if (System.getSecurityManager() != null) {
            try {
                AccessController.doPrivileged((PrivilegedExceptionAction<Object>) () -> {
                    ((InitializingBean) bean).afterPropertiesSet();
                    return null;
                }, getAccessControlContext());
            } catch (PrivilegedActionException pae) {
					throw pae.getException();
            }
        } else {
            // 调用afterPropertiesSet方法
            ((InitializingBean) bean).afterPropertiesSet();
        }
    }

    // 调用自定义的init方法,例如XML中init-method属性设置的方法
    if (mbd != null && bean.getClass() != NullBean.class) {
        String initMethodName = mbd.getInitMethodName();
        if (StringUtils.hasLength(initMethodName) &&
            !(isInitializingBean && "afterPropertiesSet".equals(initMethodName)) &&
            !mbd.isExternallyManagedInitMethod(initMethodName)) {
            invokeCustomInitMethod(beanName, bean, mbd);
        }
    }
}
           

综合上面的代码来看,

bean

初始化阶段流程主要如下:

  1. @PostConstruct

    注解修饰的方法,前提是注解驱动
  2. 实现

    InitializingBean

    接口的

    afterPropertySet()

  3. 自定义初始化方法,例如 XML 中的

    init-method

    属性设置的方法

AbstractAutowireCapableBeanFactory#applyBeanPostProcessorsAfterInitialization

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

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

下面我们简单看一下

BeanPostProcessor

接口,如下:

public interface BeanPostProcessor {

	@Nullable
	default Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
		return bean;
	}

	@Nullable
	default Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
		return bean;
	}

}
           

BeanPostProcessor

接口比较简单,就提供了两个接口回调,一个初始化前,一个初始化后。但是其它的

PostProcessor

大部门以此为基础,继承自

BeanPostProcessor

AbstractBeanFactory#registerDisposableBeanIfNecessary

protected void registerDisposableBeanIfNecessary(String beanName, Object bean, RootBeanDefinition mbd) {
    AccessControlContext acc = (System.getSecurityManager() != null ? getAccessControlContext() : null);
    // bean的作用域不是原型 && bean需要在关闭时销毁
    if (!mbd.isPrototype() && requiresDestruction(bean, mbd)) {
        if (mbd.isSingleton()) {
            // Register a DisposableBean implementation that performs all destruction
            // work for the given bean: DestructionAwareBeanPostProcessors,
            // 单例模式下注册用于销毁的bean到disposableBeans缓存,执行给定bean的所有销毁工作:
            // DestructionAwareBeanPostProcessors,DisposableBean接口,自定义销毁方法
            // DisposableBeanAdapter:使用DisposableBeanAdapter来封装用于销毁的bean
            // 见下文详解
            registerDisposableBean(beanName,
                                   new DisposableBeanAdapter(bean, beanName, mbd, getBeanPostProcessors(), acc));
        }
        else {
            // A bean with a custom scope...
            // bean是自定义作用域
            Scope scope = this.scopes.get(mbd.getScope());
            if (scope == null) {
                throw new IllegalStateException("No Scope registered for scope name '" + mbd.getScope() + "'");
            }
            // 注册一个回调,在销毁时执行,执行时机自己去管理,Spring不会帮忙调用
            scope.registerDestructionCallback(beanName,
                                              new DisposableBeanAdapter(bean, beanName, mbd, getBeanPostProcessors(), acc));
        }
    }
}
           

DisposableBeanAdapter构造函数

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

    Assert.notNull(bean, "Disposable bean must not be null");
    this.bean = bean;
    this.beanName = beanName;
    // 判断bean是否要调用DisposableBean的destroy方法
    this.invokeDisposableBean =
        (this.bean instanceof DisposableBean &&
         !beanDefinition.isExternallyManagedDestroyMethod("destroy"));
    this.nonPublicAccessAllowed = beanDefinition.isNonPublicAccessAllowed();
    this.acc = acc;
    // 获取自定义的destroy方法名,赋值给destroyMethodName
    String destroyMethodName = inferDestroyMethodIfNecessary(bean, beanDefinition);
    if (destroyMethodName != null && !(this.invokeDisposableBean && "destroy".equals(destroyMethodName)) &&
        !beanDefinition.isExternallyManagedDestroyMethod(destroyMethodName)) {
        // 获取自定义的destroy方法名赋值给destroyMethodName
        this.destroyMethodName = destroyMethodName;
        Method destroyMethod = determineDestroyMethod(destroyMethodName);
        // 如果判定后的destroyMethod为空,抛出异常
        if (destroyMethod == null) {
            if (beanDefinition.isEnforceDestroyMethod()) {
                throw new BeanDefinitionValidationException("Could not find a destroy method named '" +
                                                            destroyMethodName + "' on bean with name '" + beanName + "'");
            }
        }
        // 如果判定后的destroyMethod不为空
        else {
            // 获取destroyMethod的方法参数
            Class<?>[] paramTypes = destroyMethod.getParameterTypes();
            // 参数长度大于1抛出异常,自定义的destroy方法最多只允许有一个boolean参数
            if (paramTypes.length > 1) {
                throw new BeanDefinitionValidationException("Method '" + destroyMethodName + "' of bean '" +
                                                            beanName + "' has more than one parameter - not supported as destroy method");
            }
            // 参数长度等于1 && 不是boolean类型,抛出异常
            else if (paramTypes.length == 1 && boolean.class != paramTypes[0]) {
                throw new BeanDefinitionValidationException("Method '" + destroyMethodName + "' of bean '" +
                                                            beanName + "' has a non-boolean parameter - not supported as destroy method");
            }
            destroyMethod = ClassUtils.getInterfaceMethodIfPossible(destroyMethod);
        }
        this.destroyMethod = destroyMethod;
    }
    // 查找DestructionAwareBeanPostProcessors,并赋值给this.beanPostProcessors,见下文详解
    this.beanPostProcessors = filterPostProcessors(postProcessors, bean);
}
           

DisposableBeanAdapter#filterPostProcessors

private List<DestructionAwareBeanPostProcessor> filterPostProcessors(List<BeanPostProcessor> processors, Object bean) {
    List<DestructionAwareBeanPostProcessor> filteredPostProcessors = null;
    // processors长度不为空
    if (!CollectionUtils.isEmpty(processors)) {
        // 遍历processors
        for (BeanPostProcessor processor : processors) {
            // 如果processor的类型是DestructionAwareBeanPostProcessor
            if (processor instanceof DestructionAwareBeanPostProcessor) {
                DestructionAwareBeanPostProcessor dabpp = (DestructionAwareBeanPostProcessor) processor;
                // 如果bean实际需要通过此后置处理器进行销毁,则添加到filteredPostProcessors
                if (dabpp.requiresDestruction(bean)) {
                    filteredPostProcessors.add(dabpp);
                }
            }
        }
    }
    return filteredPostProcessors;
}
           

上面的代码主要就是判断如果

BeanPostProcessor

DestructionAwareBeanPostProcessor

并且

requiresDestruction()

返回

true

代表需要通过后置处理器进行销毁实例,将该

BeanPostProcessor

添加到

filteredPostProcessors

中。

下面我们简单看一下

DestructionAwareBeanPostProcessor

接口的定义:

public interface DestructionAwareBeanPostProcessor extends BeanPostProcessor {

	/**
	 * bean 销毁前阶段生命周期回调方法
	 */
	void postProcessBeforeDestruction(Object bean, String beanName) throws BeansException;

	/**
	 * bean 实例是否要由此后置处理器进行实例的销毁
	 */
	default boolean requiresDestruction(Object bean) {
		return true;
	}

}
           

可以看到其也是继承于

BeanPostProcessor

,主要提供两个方法一个是

bean

销毁前的生命周期方法回调,另一个是判定

bean

实例是否要由此后置处理器进行实例的销毁。

DefaultListableBeanFactory#destroySingletons

因为基本上

BeanFactory

就只会使用

DefaultListableBeanFactory

这一个最终实现,所以我们这里分析一下这里的销毁单例

bean

的方法。

public void destroySingletons() {
    // 调用父类的销毁所有单例bean方法
    super.destroySingletons();
    updateManualSingletonNames(Set::clear, set -> !set.isEmpty());
    // 清除所有bean类型的缓存
    clearByTypeCache();
}

// DefaultSingletonBeanRegistry.java
public void destroySingletons() {
    if (logger.isTraceEnabled()) {
        logger.trace("Destroying singletons in " + this);
    }
    synchronized (this.singletonObjects) {
        this.singletonsCurrentlyInDestruction = true;
    }

    String[] disposableBeanNames;
    // 获取所有需要销毁的bean
    synchronized (this.disposableBeans) { 
        disposableBeanNames = StringUtils.toStringArray(this.disposableBeans.keySet());
    } 
    // 根据注册顺序,倒着遍历,销毁bean
    for (int i = disposableBeanNames.length - 1; i >= 0; i--) {
        destroySingleton(disposableBeanNames[i]);
    }

    this.containedBeanMap.clear();
    this.dependentBeanMap.clear();
    this.dependenciesForBeanMap.clear();
    // 从缓存中清除所有单例实例
    clearSingletonCache();
}

// DefaultSingletonBeanRegistry.java
public void destroySingleton(String beanName) {
    // Remove a registered singleton of the given name, if any.
    // 从缓存中清除所有当前beanName单例实例
    removeSingleton(beanName);

    // Destroy the corresponding DisposableBean instance.
    DisposableBean disposableBean;
    // 加锁,从disposableBeans中将当前bean移除
    synchronized (this.disposableBeans) {
        disposableBean = (DisposableBean) this.disposableBeans.remove(beanName);
    }
    // 销毁bean
    destroyBean(beanName, disposableBean);
}

protected void destroyBean(String beanName, @Nullable DisposableBean bean) {
    // Trigger destruction of dependent beans first...
    Set<String> dependencies;
    // 加锁,从dependentBeanMap中移除当前bean
    synchronized (this.dependentBeanMap) {
        // Within full synchronization in order to guarantee a disconnected Set
        dependencies = this.dependentBeanMap.remove(beanName);
    }
    if (dependencies != null) {
        if (logger.isTraceEnabled()) {
            logger.trace("Retrieved dependent beans for bean '" + beanName + "': " + dependencies);
        }
        // dependencies不为空,说明,当前bean有其它依赖的bean,遍历去销毁
        for (String dependentBeanName : dependencies) {
            destroySingleton(dependentBeanName);
        }
    }

    // Actually destroy the bean now...
    // bean不为空,调用destroy方法真正的开始进行销毁
    if (bean != null) {
        try {
            bean.destroy();
        }
        catch (Throwable ex) {
            if (logger.isWarnEnabled()) {
                logger.warn("Destruction of bean with name '" + beanName + "' threw an exception", ex);
            }
        }
    }

    // Trigger destruction of contained beans...
    Set<String> containedBeans;
    synchronized (this.containedBeanMap) {
        // Within full synchronization in order to guarantee a disconnected Set
        containedBeans = this.containedBeanMap.remove(beanName);
    }
    if (containedBeans != null) {
        for (String containedBeanName : containedBeans) {
            destroySingleton(containedBeanName);
        }
    }

    // Remove destroyed bean from other beans' dependencies.
    synchronized (this.dependentBeanMap) {
        for (Iterator<Map.Entry<String, Set<String>>> it = this.dependentBeanMap.entrySet().iterator(); it.hasNext();) {
            Map.Entry<String, Set<String>> entry = it.next();
            Set<String> dependenciesToClean = entry.getValue();
            dependenciesToClean.remove(beanName);
            if (dependenciesToClean.isEmpty()) {
                it.remove();
            }
        }
    }

    // Remove destroyed bean's prepared dependency information.
    this.dependenciesForBeanMap.remove(beanName);
}
           

DisposableBeanAdapter#destroy

public void destroy() {
    // 如果beanPostProcessors不为空
    if (!CollectionUtils.isEmpty(this.beanPostProcessors)) {
        // 遍历beanPostProcessors调用postProcessBeforeDestruction()
        for (DestructionAwareBeanPostProcessor processor : this.beanPostProcessors) {
            processor.postProcessBeforeDestruction(this.bean, this.beanName);
        }
    }

    if (this.invokeDisposableBean) {
        if (logger.isTraceEnabled()) {
            logger.trace("Invoking destroy() on bean with name '" + this.beanName + "'");
        }
        try {
            if (System.getSecurityManager() != null) {
                AccessController.doPrivileged((PrivilegedExceptionAction<Object>) () -> {
                    ((DisposableBean) this.bean).destroy();
                    return null;
                }, this.acc);
            }
            else {
                // 调用实现了DisposableBean的destroy()
                ((DisposableBean) this.bean).destroy();
            }
        }
        catch (Throwable ex) {
            String msg = "Invocation of destroy method failed on bean with name '" + this.beanName + "'";
            if (logger.isDebugEnabled()) {
                logger.warn(msg, ex);
            }
            else {
                logger.warn(msg + ": " + ex);
            }
        }
    }
    // 调用自定义的destroy方法
    if (this.destroyMethod != null) {
        invokeCustomDestroyMethod(this.destroyMethod);
    }
    else if (this.destroyMethodName != null) {
        Method methodToInvoke = determineDestroyMethod(this.destroyMethodName);
        if (methodToInvoke != null) {          invokeCustomDestroyMethod(ClassUtils.getInterfaceMethodIfPossible(methodToInvoke));
        }
    }
}
           

总得来说上面方法主要分为三步:

  1. 回调实现了

    DestructionAwareBeanPostProcessor

    接口的

    postProcessBeforeDestruction

    方法,

    InitDestoryAnnotationBeanPostProcessor

    postProcessBeforeDestruction()

    中会执行标注了

    @PreDestory

    注解的方法。
  2. 调用实现了

    DisposableBean

    接口的

    destroy()

  3. 调用自定义实现的

    destroyMethod

    ,例如 XML 中的

    destory

    属性指定的方法

总结

本文主要介绍了

createBean()

流程,我们可以重新梳理一下思路:

  1. 进行

    bean

    的实例化前方法回调,如果返回非空,跳过后面步骤
  2. 创建

    bean

    的实例,如果是构造函数注入会选择最适合的构造函数进行参数自动注入,否则调用默认的无参构造进行实例化

    bean

  3. 如果

    bean

    允许提前曝光,将

    beanName

    对应的

    ObjectFactory

    放入

    singletonFactories

    缓存中。
  4. bean

    的属性赋值阶段,首先调用

    bean

    实例化后方法回调,返回

    false

    会跳过后面的赋值阶段;判断是否是按照名称或者类型自动注入,是则进行属性自动注入。接着调用处理属性值的后置处理方法,首先调用Spring5.1版本新加的方法,如果返回的属性为空,再调用以前版本的方法,如果为空,直接返回,没必要再走后面的实际赋值阶段。
  5. bean

    的初始化阶段,首先是调用可以获取相应资源的一些

    Aware

    接口;然后调用

    bean

    初始化前回调方法 (

    InitDestroyAnnotationBeanPostProcessor

    postProcessBeforeInitialization()

    中会执行

    标注了

    @PostConstruct

    注解的方法),接着调用重写的

    afterPropertiesSet()

    和自定义的初始化方法;最后进行

    bean

    初始化后回调方法。
  6. 注册销毁

    bean

    的方法。
  7. 最后返回

    bean

    的实例。

最后,我模仿 Spring 写了一个精简版,代码会持续更新,现在是

0.0.3

版本。地址:https://github.com/leisurexi/tiny-spring。访问新博客地址,观看效果更佳 https://leisurexi.github.io/

参考

  • 《Spring 源码深度解析》—— 郝佳

继续阅读