bean加载三:bean创建

接下来以单例模式为例,一起看看在前面那么多的准备工作后,现在是如何创建 bean 对象的。

if (mbd.isSingleton()) {
    sharedInstance = getSingleton(beanName, () -> {
        try {
            return createBean(beanName, mbd, args);
        }
        catch (BeansException ex) {
            // Explicitly remove instance from singleton cache: It might have been put there
            // eagerly by the creation process, to allow for circular reference resolution.
            // Also remove any beans that received a temporary reference to the bean.
            // 显式从单例缓存中删除 Bean 实例
            // 因为单例模式下为了解决循环依赖,可能他已经存在了,所以销毁它
            destroySingleton(beanName);
            throw ex;
        }
    });
    bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
}

7.1 getSingleton

public Object getSingleton(String beanName, ObjectFactory singletonFactory) {
    Assert.notNull(beanName, "Bean name must not be null");
    synchronized (this.singletonObjects) {
        // 从缓存中检查一遍
        // 因为 singleton 模式其实就是复用已经创建的 bean 所以这步骤必须检查
        Object singletonObject = this.singletonObjects.get(beanName);
        if (singletonObject == null) {
            // 如果当前单例对象正在销毁
            if (this.singletonsCurrentlyInDestruction) {
                throw new BeanCreationNotAllowedException(beanName,
                        "Singleton bean creation not allowed while singletons of this factory are in destruction " +
                        "(Do not request a bean from a BeanFactory in a destroy method implementation!)");
            }
            if (logger.isDebugEnabled()) {
                logger.debug("Creating shared instance of singleton bean '" + beanName + "'");
            }
            // 加载前置处理,校验beanName没有正在创建
            beforeSingletonCreation(beanName);
            boolean newSingleton = false;
            boolean recordSuppressedExceptions = (this.suppressedExceptions == null);
            if (recordSuppressedExceptions) {
                this.suppressedExceptions = new LinkedHashSet<>();
            }
            try {
                // 获取单例对象
                singletonObject = singletonFactory.getObject();
                newSingleton = true;
            }
            catch (IllegalStateException ex) {
                // Has the singleton object implicitly appeared in the meantime ->
                // if yes, proceed with it since the exception indicates that state.
                singletonObject = this.singletonObjects.get(beanName);
                if (singletonObject == null) {
                    throw ex;
                }
            }
            catch (BeanCreationException ex) {
                if (recordSuppressedExceptions) {
                    for (Exception suppressedException : this.suppressedExceptions) {
                        ex.addRelatedCause(suppressedException);
                    }
                }
                throw ex;
            }
            finally {
                if (recordSuppressedExceptions) {
                    this.suppressedExceptions = null;
                }
                // 后置处理
                afterSingletonCreation(beanName);
            }
            // 加入缓存中
            if (newSingleton) {
                addSingleton(beanName, singletonObject);
            }
        }
        return singletonObject;
    }
}

核心的还是 singletonFactory.getObject

7.2 createBean

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;

    // 确保此时的 bean 已经被解析了
    // 如果获取的class 属性不为null,则克隆该 BeanDefinition
    // 主要是因为该动态解析的 class 无法保存到到共享的 BeanDefinition
    Class resolvedClass = resolveBeanClass(mbd, beanName);
    if (resolvedClass != null && !mbd.hasBeanClass() && mbd.getBeanClassName() != null) {
        mbdToUse = new RootBeanDefinition(mbd);
        mbdToUse.setBeanClass(resolvedClass);
    }

    try {
        // 验证 lookup-method 和 replace-method 配置
        mbdToUse.prepareMethodOverrides();
    }
    catch (BeanDefinitionValidationException ex) {
        throw new BeanDefinitionStoreException(mbdToUse.getResourceDescription(),
                beanName, "Validation of method overrides failed", ex);
    }

    try {
        // 实例化的前置处理
        // 给 BeanPostProcessors 一个机会用来返回一个代理类而不是真正的类实例
        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 + "'");
        }
        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);
    }
}

这里有两个核心逻辑

7.2.1 resolveBeforeInstantiation

protected Object resolveBeforeInstantiation(String beanName, RootBeanDefinition mbd) {
    Object bean = null;
    if (!Boolean.FALSE.equals(mbd.beforeInstantiationResolved)) {
        // Make sure bean class is actually resolved at this point.
        if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
            Class targetType = determineTargetType(beanName, mbd);
            if (targetType != null) {
                // 前置
                bean = applyBeanPostProcessorsBeforeInstantiation(targetType, beanName);
                if (bean != null) {
                    // 后置
                    bean = applyBeanPostProcessorsAfterInitialization(bean, beanName);
                }
            }
        }
        mbd.beforeInstantiationResolved = (bean != null);
    }
    return bean;
}

这里的前置处理指的是执行类型为InstantiationAwareBeanPostProcessor的postProcessBeforeInstantiation方法,用于在对象实例化之前返回方法中设置的值,会跳过接下来的对象实例化、初始化流程。

protected Object applyBeanPostProcessorsBeforeInstantiation(Class beanClass, String beanName) {
    for (BeanPostProcessor bp : getBeanPostProcessors()) {
        // 找到类型为 InstantiationAwareBeanPostProcessor 的 BeanPostProcessor
        if (bp instanceof InstantiationAwareBeanPostProcessor) {
            InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
            Object result = ibp.postProcessBeforeInstantiation(beanClass, beanName);
            if (result != null) {
                return result;
            }
        }
    }
    return null;
}

后置处理指得是获取 BeanPostProcessor 数组,执行 postProcessAfterInitialization 方法

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

    Object result = existingBean;
    // 获取 BeanPostProcessor 数组
    for (BeanPostProcessor processor : getBeanPostProcessors()) {
        // 循环调用 postProcessAfterInitialization 方法,如果为空立即返回
        Object current = processor.postProcessAfterInitialization(result, beanName);
        if (current == null) {
            return result;
        }
        result = current;
    }
    return result;
}

7.2.2 doCreateBean

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

  // Instantiate the bean.
  // BeanWrapper 是对 Bean 的包装,其接口中所定义的功能很简单包括设置获取被包装的对象,获取被包装 bean 的属性描述器
  BeanWrapper instanceWrapper = null;
  // 单例模型,则从未完成的 FactoryBean 缓存中删除
  if (mbd.isSingleton()) {
    instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
  }
  // 使用合适的实例化策略来创建新的实例:工厂方法、构造函数自动注入、简单初始化
  if (instanceWrapper == null) {
    instanceWrapper = createBeanInstance(beanName, mbd, args);
  }
  // 包装的实例对象
  final Object bean = instanceWrapper.getWrappedInstance();
  // 包装的实例对象的类型
  Class beanType = instanceWrapper.getWrappedClass();
  if (beanType != NullBean.class) {
    mbd.resolvedTargetType = beanType;
  }

  // Allow post-processors to modify the merged bean definition.
  // 判断是否有后置处理
  // 如果有后置处理,则允许后置处理修改 BeanDefinition
  synchronized (mbd.postProcessingLock) {
    if (!mbd.postProcessed) {
      try {
        applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
      }
      catch (Throwable ex) {
        throw new BeanCreationException(mbd.getResourceDescription(), beanName,
            "Post-processing of merged bean definition failed", ex);
      }
      mbd.postProcessed = true;
    }
  }

  // Eagerly cache singletons to be able to resolve circular references
  // even when triggered by lifecycle interfaces like BeanFactoryAware.
  // 解决单例循环依赖
  boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences &&
      isSingletonCurrentlyInCreation(beanName));
  if (earlySingletonExposure) {
    if (logger.isTraceEnabled()) {
      logger.trace("Eagerly caching bean '" + beanName +
          "' to allow for resolving potential circular references");
    }
    // 提前将创建的 bean 实例加入到 singletonFactories 中
    // 这里是为了后期避免循环依赖
    addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
  }

  // Initialize the bean instance.
  // 开始初始化 bean 实例对象
  Object exposedObject = bean;
  try {
    // 对 bean 进行填充,将各个属性值注入,其中,可能存在依赖于其他 bean 的属性
    // 则会递归初始依赖 bean
    populateBean(beanName, mbd, instanceWrapper);
    // 调用初始化方法
    exposedObject = initializeBean(beanName, exposedObject, mbd);
  }
  catch (Throwable ex) {
    if (ex instanceof BeanCreationException && beanName.equals(((BeanCreationException) ex).getBeanName())) {
      throw (BeanCreationException) ex;
    }
    else {
      throw new BeanCreationException(
          mbd.getResourceDescription(), beanName, "Initialization of bean failed", ex);
    }
  }

  // 循环依赖处理
  if (earlySingletonExposure) {
    Object earlySingletonReference = getSingleton(beanName, false);
    // 只有在存在循环依赖的情况下,earlySingletonReference 才不会为空
    if (earlySingletonReference != null) {
      // 如果 exposedObject 没有在初始化方法中被改变,也就是没有被增强
      if (exposedObject == bean) {
        exposedObject = earlySingletonReference;
      }
      // 处理依赖
      else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) {
        String[] dependentBeans = getDependentBeans(beanName);
        Set 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.
  // 注册 bean
  try {
    registerDisposableBeanIfNecessary(beanName, bean, mbd);
  }
  catch (BeanDefinitionValidationException ex) {
    throw new BeanCreationException(
        mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex);
  }

  return exposedObject;
}

这个方法主要包括几个部分:
1.通过 createBeanInstance 获取 bean 实例对象
2.执行 MergedBeanDefinitionPostProcessors 类型的BeanPostProcessors,MergedBeanDefinitionPostProcessors 又一个很重要的实现类 AutowiredAnnotationBeanPostProcessor 实现了@Autowired和@Value注解
3.初始化对象,填充依赖
4.处理依赖
5.注册bean
接下来一部分一部分的看一下

7.2.2.1 createBeanInstance

protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) {
    // Make sure bean class is actually resolved at this point.
    // 解析 bean ,将 bean 类名解析为 class 引用。
    Class beanClass = resolveBeanClass(mbd, beanName);

    if (beanClass != null && !Modifier.isPublic(beanClass.getModifiers()) && !mbd.isNonPublicAccessAllowed()) {
        throw new BeanCreationException(mbd.getResourceDescription(), beanName,
                "Bean class isn't public, and non-public access not allowed: " + beanClass.getName());
    }

    // 如果存在 Supplier 回调,则使用给定的回调方法初始化策略
    Supplier instanceSupplier = mbd.getInstanceSupplier();
    if (instanceSupplier != null) {
        return obtainFromSupplier(instanceSupplier, beanName);
    }

    // 使用 FactoryBean 的 factory-method 来创建,支持静态工厂和实例工厂
    if (mbd.getFactoryMethodName() != null) {
        return instantiateUsingFactoryMethod(beanName, mbd, args);
    }

    // Shortcut when re-creating the same bean...
    boolean resolved = false;
    boolean autowireNecessary = false;
    if (args == null) {
        synchronized (mbd.constructorArgumentLock) {
            // 如果已缓存的解析的构造函数或者工厂方法不为空,则可以利用构造函数解析
            // 因为需要根据参数确认到底使用哪个构造函数,该过程比较消耗性能,所有采用缓存机制
            if (mbd.resolvedConstructorOrFactoryMethod != null) {
                resolved = true;
                autowireNecessary = mbd.constructorArgumentsResolved;
            }
        }
    }
    // 已经解析好了,直接注入即可
    if (resolved) {
        // autowire 自动注入,调用构造函数自动注入
        if (autowireNecessary) {
            return autowireConstructor(beanName, mbd, null, null);
        }
        else {
            // 使用默认构造函数构造
            return instantiateBean(beanName, mbd);
        }
    }

    // Candidate constructors for autowiring?
    Constructor[] ctors = determineConstructorsFromBeanPostProcessors(beanClass, beanName);
    if (ctors != null || mbd.getResolvedAutowireMode() == AUTOWIRE_CONSTRUCTOR ||
            mbd.hasConstructorArgumentValues() || !ObjectUtils.isEmpty(args)) {
        return autowireConstructor(beanName, mbd, ctors, args);
    }

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

    // No special handling: simply use no-arg constructor.
    return instantiateBean(beanName, mbd);
}

实例化bean是一个很复杂的过程,总的来说有4种方式获取bean实例:

  • 如果存在 Supplier 回调,则调用 obtainFromSupplier() 进行初始化
  • 如果存在工厂方法,则使用工厂方法进行初始化
  • 指定的构造函数
  • 默认的构造函数
    下面简单分析下这4种情况:

1.Supplier 回调

对应的代码是

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

接下来继续看 obtainFromSupplier 方法

protected BeanWrapper obtainFromSupplier(Supplier instanceSupplier, String beanName) {
    Object instance;
    // 判断 beanName 对应的实例对象是否正在创建中
    String outerBean = this.currentlyCreatedBean.get();
    this.currentlyCreatedBean.set(beanName);
    try {
        // 调用 Supplier 的 get(),返回一个对象
        instance = instanceSupplier.get();
    }
    finally {
        if (outerBean != null) {
            this.currentlyCreatedBean.set(outerBean);
        }
        else {
            this.currentlyCreatedBean.remove();
        }
    }

    if (instance == null) {
        instance = new NullBean();
    }
    // 根据对象构造 BeanWrapper 对象
    BeanWrapper bw = new BeanWrapperImpl(instance);
    // 初始化 BeanWrapper
    initBeanWrapper(bw);
    return bw;
}

2. instantiateUsingFactoryMethod

ps:instantiateUsingFactoryMethod 方法体实在是太大了,这里害怕自己分析的不够清晰。推荐一篇文章。我会把 instantiateUsingFactoryMethod 拆分开,分析一些重要的逻辑,接下来就开始。

protected BeanWrapper instantiateUsingFactoryMethod(
    String beanName, RootBeanDefinition mbd, @Nullable Object[] explicitArgs) {

  return new ConstructorResolver(this).instantiateUsingFactoryMethod(beanName, mbd, explicitArgs);
}

这里首先构造了一个 ConstructorResolver 对象,ConstructorResolver 可以理解为beanFactory的委托类,委托它来完成实例对象的创建和初始化。

2.1 BeanWrapperImpl

// 构造 BeanWrapperImpl 对象
BeanWrapperImpl bw = new BeanWrapperImpl();
// 向BeanWrapper对象中添加 ConversionService 对象和属性编辑器 PropertyEditor 对象
this.beanFactory.initBeanWrapper(bw);

2.2 找到实例化方法

什么是实例工厂和静态工厂

// 有工厂名
if (factoryBeanName != null) {
  if (factoryBeanName.equals(beanName)) {
    throw new BeanDefinitionStoreException(mbd.getResourceDescription(), beanName,
        "factory-bean reference points back to the same bean definition");
  }
  // 获取 工厂 对象
  factoryBean = this.beanFactory.getBean(factoryBeanName);
  if (mbd.isSingleton() && this.beanFactory.containsSingleton(beanName)) {
    throw new ImplicitlyAppearedSingletonException();
  }
  factoryClass = factoryBean.getClass();
  isStatic = false;
}
else {
  // It's a static factory method on the bean class.
  // 没有工厂名,一定是静态工厂
  if (!mbd.hasBeanClass()) {
    throw new BeanDefinitionStoreException(mbd.getResourceDescription(), beanName,
        "bean definition declares neither a bean class nor a factory-bean reference");
  }
  factoryBean = null;
  factoryClass = mbd.getBeanClass();
  isStatic = true;
}

2.3 找到实例化方法对应参数

// 1.调用getBean时传递的参数不为空
if (explicitArgs != null) {
  argsToUse = explicitArgs;
}
// 2.在本方法最后保存的缓存
else {
  Object[] argsToResolve = null;
  synchronized (mbd.constructorArgumentLock) {
    factoryMethodToUse = (Method) mbd.resolvedConstructorOrFactoryMethod;
    if (factoryMethodToUse != null && mbd.constructorArgumentsResolved) {
      // Found a cached factory method...
      argsToUse = mbd.resolvedConstructorArguments;
      if (argsToUse == null) {
        argsToResolve = mbd.preparedConstructorArguments;
      }
    }
  }
  // 转换缓存中的参数类型,比如将 "1" -> 1
  if (argsToResolve != null) {
    argsToUse = resolvePreparedArguments(beanName, mbd, bw, factoryMethodToUse, argsToResolve, true);
  }
}

2.4 寻找合适的实例化方法

// 获取工厂方法的类全名称
factoryClass = ClassUtils.getUserClass(factoryClass);
// 获取所有待定方法
List candidateList = null;
if (mbd.isFactoryMethodUnique) {
  if (factoryMethodToUse == null) {
    factoryMethodToUse = mbd.getResolvedFactoryMethod();
  }
  if (factoryMethodToUse != null) {
    candidateList = Collections.singletonList(factoryMethodToUse);
  }
}
if (candidateList == null) {
  candidateList = new ArrayList<>();
  // 检索所有方法,这里是对方法进行过滤
  Method[] rawCandidates = getCandidateMethods(factoryClass, mbd);
  for (Method candidate : rawCandidates) {
    // 如果有static 且为工厂方法,则添加到 candidateSet 中
    if (Modifier.isStatic(candidate.getModifiers()) == isStatic && mbd.isFactoryMethod(candidate)) {
      candidateList.add(candidate);
    }
  }
}

// 如果方法唯一且输入参数为空且配置文件中没有配置参数,直接创建对象并且返回
if (candidateList.size() == 1 && explicitArgs == null && !mbd.hasConstructorArgumentValues()) {
  Method uniqueCandidate = candidateList.get(0);
  if (uniqueCandidate.getParameterCount() == 0) {
    mbd.factoryMethodToIntrospect = uniqueCandidate;
    synchronized (mbd.constructorArgumentLock) {
      mbd.resolvedConstructorOrFactoryMethod = uniqueCandidate;
      mbd.constructorArgumentsResolved = true;
      mbd.resolvedConstructorArguments = EMPTY_ARGS;
    }
    bw.setBeanInstance(instantiate(beanName, mbd, factoryBean, uniqueCandidate, EMPTY_ARGS));
    return bw;
  }
}

2.5 解析构造函数的参数

Method[] candidates = candidateList.toArray(new Method[0]);
// 排序,public方法在其他类型方法之前,public根据参数多少倒排
AutowireUtils.sortFactoryMethods(candidates);

// 用于承载解析后的构造函数参数的值
ConstructorArgumentValues resolvedValues = null;
boolean autowiring = (mbd.getResolvedAutowireMode() == AutowireCapableBeanFactory.AUTOWIRE_CONSTRUCTOR);
int minTypeDiffWeight = Integer.MAX_VALUE;
Set ambiguousFactoryMethods = null;

int minNrOfArgs;
if (explicitArgs != null) {
    minNrOfArgs = explicitArgs.length;
}
else {
    // getBean() 没有传递参数,则需要解析保存在 BeanDefinition 构造函数中指定的参数
    if (mbd.hasConstructorArgumentValues()) {
        ConstructorArgumentValues cargs = mbd.getConstructorArgumentValues();
        resolvedValues = new ConstructorArgumentValues();
        // 解析构造函数的参数
        // 将该 bean 的构造函数参数解析为 resolvedValues 对象,其中会涉及到其他 bean
        minNrOfArgs = resolveConstructorArguments(beanName, mbd, bw, cargs, resolvedValues);
    }
    else {
        minNrOfArgs = 0;
    }
}

2.6 选择合适的构造函数

for (Method candidate : candidates) {
    Class[] paramTypes = candidate.getParameterTypes();

    if (paramTypes.length >= minNrOfArgs) {
        ArgumentsHolder argsHolder;

        // getBean()传递了参数
        if (explicitArgs != null) {
            // Explicit arguments given -> arguments length must match exactly.
            if (paramTypes.length != explicitArgs.length) {
                continue;
            }
            argsHolder = new ArgumentsHolder(explicitArgs);
        }
        else {
            // 为提供参数,解析构造参数
            try {
                String[] paramNames = null;
                // 获取 ParameterNameDiscoverer 对象
                // ParameterNameDiscoverer 是用于解析方法和构造函数的参数名称的接口,为参数名称探测器
                ParameterNameDiscoverer pnd = this.beanFactory.getParameterNameDiscoverer();
                if (pnd != null) {
                    // 获取指定构造函数的参数名称
                    paramNames = pnd.getParameterNames(candidate);
                }
                // 在已经解析的构造函数参数值的情况下,创建一个参数持有者对象
                argsHolder = createArgumentArray(beanName, mbd, resolvedValues, bw,
                        paramTypes, paramNames, candidate, autowiring, candidates.length == 1);
            }
            catch (UnsatisfiedDependencyException ex) {
                if (logger.isTraceEnabled()) {
                    logger.trace("Ignoring factory method [" + candidate + "] of bean '" + beanName + "': " + ex);
                }
                // Swallow and try next overloaded factory method.
                if (causes == null) {
                    causes = new LinkedList<>();
                }
                causes.add(ex);
                continue;
            }
        }

        // isLenientConstructorResolution 判断解析构造函数的时候是否以宽松模式还是严格模式
        // 严格模式:解析构造函数时,必须所有的都需要匹配,否则抛出异常
        // 宽松模式:使用具有"最接近的模式"进行匹配
        // typeDiffWeight:类型差异权重
        int typeDiffWeight = (mbd.isLenientConstructorResolution() ?
                argsHolder.getTypeDifferenceWeight(paramTypes) : argsHolder.getAssignabilityWeight(paramTypes));
        // 代表最接近的类型匹配,则选择作为构造函数
        if (typeDiffWeight < minTypeDiffWeight) {
            factoryMethodToUse = candidate;
            argsHolderToUse = argsHolder;
            argsToUse = argsHolder.arguments;
            minTypeDiffWeight = typeDiffWeight;
            ambiguousFactoryMethods = null;
        }
        // 如果具有相同参数数量的方法具有相同的类型差异权重,则收集此类型选项
        // 但是,仅在非宽松构造函数解析模式下执行该检查,并显式忽略重写方法(具有相同的参数签名)
        else if (factoryMethodToUse != null && typeDiffWeight == minTypeDiffWeight &&
                !mbd.isLenientConstructorResolution() &&
                paramTypes.length == factoryMethodToUse.getParameterCount() &&
                !Arrays.equals(paramTypes, factoryMethodToUse.getParameterTypes())) {
            if (ambiguousFactoryMethods == null) {
                ambiguousFactoryMethods = new LinkedHashSet<>();
                ambiguousFactoryMethods.add(factoryMethodToUse);
            }
            ambiguousFactoryMethods.add(candidate);
        }
    }
}

2.7 校验与缓存

// 没有可执行的工厂方法,抛出异常
if (factoryMethodToUse == null || argsToUse == null) {
    if (causes != null) {
        UnsatisfiedDependencyException ex = causes.removeLast();
        for (Exception cause : causes) {
            this.beanFactory.onSuppressedException(cause);
        }
        throw ex;
    }
    // 参数类型
    List argTypes = new ArrayList<>(minNrOfArgs);
    // getBean()传入的参数不为空
    if (explicitArgs != null) {
        for (Object arg : explicitArgs) {
            argTypes.add(arg != null ? arg.getClass().getSimpleName() : "null");
        }
    }
    // BeanDefinition 中的参数类型
    else if (resolvedValues != null) {
        Set valueHolders = new LinkedHashSet<>(resolvedValues.getArgumentCount());
        valueHolders.addAll(resolvedValues.getIndexedArgumentValues().values());
        valueHolders.addAll(resolvedValues.getGenericArgumentValues());
        for (ValueHolder value : valueHolders) {
            String argType = (value.getType() != null ? ClassUtils.getShortName(value.getType()) :
                    (value.getValue() != null ? value.getValue().getClass().getSimpleName() : "null"));
            argTypes.add(argType);
        }
    }
    String argDesc = StringUtils.collectionToCommaDelimitedString(argTypes);
    throw new BeanCreationException(mbd.getResourceDescription(), beanName,
            "No matching factory method found: " +
            (mbd.getFactoryBeanName() != null ?
                "factory bean '" + mbd.getFactoryBeanName() + "'; " : "") +
            "factory method '" + mbd.getFactoryMethodName() + "(" + argDesc + ")'. " +
            "Check that a method with the specified name " +
            (minNrOfArgs > 0 ? "and arguments " : "") +
            "exists and that it is " +
            (isStatic ? "static" : "non-static") + ".");
}
else if (void.class == factoryMethodToUse.getReturnType()) {
    throw new BeanCreationException(mbd.getResourceDescription(), beanName,
            "Invalid factory method '" + mbd.getFactoryMethodName() +
            "': needs to have a non-void return type!");
}
else if (ambiguousFactoryMethods != null) {
    throw new BeanCreationException(mbd.getResourceDescription(), beanName,
            "Ambiguous factory method matches found in bean '" + beanName + "' " +
            "(hint: specify index/type/name arguments for simple parameters to avoid type ambiguities): " +
            ambiguousFactoryMethods);
}

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

到此通过FactoryBean获取对象实例就分析完了

3. autowireConstructor(指定的构造函数)

与第二种大同小异,方法体也十分的长。总的来说就是:寻找合适的构造函数和构造函数的参数,然后使用不同的策略初始化bean对象。

4.instantiateBean(默认的构造函数)

这个就比较简单了

回到AbstractAutowireCapableBeanFactory.doCreateBean中

boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences &&
        isSingletonCurrentlyInCreation(beanName));
if (earlySingletonExposure) {
    if (logger.isTraceEnabled()) {
        logger.trace("Eagerly caching bean '" + beanName +
                "' to allow for resolving potential circular references");
    }
    // 提前将创建的 bean 实例加入到 singletonFactories 中
    // 这里是为了后期避免循环依赖
    addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
}

addSingletonFactory用于添加FactoryBean到三级缓存中,getEarlyBeanReference用于解决在循环依赖的情况下AOP代理类的提前暴露问题。
接下来继续看populateBean给对象做属性填充

7.2.2.2 populateBean

protected void populateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw) {
    // 没有实例化对象
    if (bw == null) {
        // 有属性,则抛出 BeanCreationException 异常
        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;
        }
    }

    // 在设置属性之前给 InstantiationAwareBeanPostProcessors 最后一次改变 bean 的机会
    boolean continueWithPropertyPopulation = true;

    if (!mbd.isSynthetic() // bean 不是"合成"的,即未由应用程序本身定义
            && hasInstantiationAwareBeanPostProcessors()) { // // 是否持有 InstantiationAwareBeanPostProcessor
        for (BeanPostProcessor bp : getBeanPostProcessors()) {
            if (bp instanceof InstantiationAwareBeanPostProcessor) {
                InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
                if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {
                    continueWithPropertyPopulation = false;
                    break;
                }
            }
        }
    }

    // 如果后续处理器发出停止填充命令,则终止后续操作
    if (!continueWithPropertyPopulation) {
        return;
    }

    // bean 的属性值
    PropertyValues pvs = (mbd.hasPropertyValues() ? mbd.getPropertyValues() : null);

    // 自动注入
    int resolvedAutowireMode = mbd.getResolvedAutowireMode();
    if (resolvedAutowireMode == AUTOWIRE_BY_NAME || resolvedAutowireMode == AUTOWIRE_BY_TYPE) {
        // 将 PropertyValues 封装成 MutablePropertyValues 对象
        // MutablePropertyValues 允许对属性进行简单的操作,并提供构造函数以支持Map的深度复制和构造。
        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();
        }
        // 遍历 BeanPostProcessor 数组
        for (BeanPostProcessor bp : getBeanPostProcessors()) {
            if (bp instanceof InstantiationAwareBeanPostProcessor) {
                InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
                // 对所有需要依赖检查的属性进行后处理
                PropertyValues pvsToUse = ibp.postProcessProperties(pvs, bw.getWrappedInstance(), beanName);
                if (pvsToUse == null) {
                    // 从 bw 对象中提取 PropertyDescriptor 结果集
                    // PropertyDescriptor:可以通过一对存取方法提取一个属性
                    if (filteredPds == null) {
                        filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
                    }
                    pvsToUse = ibp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName);
                    if (pvsToUse == null) {
                        return;
                    }
                }
                pvs = pvsToUse;
            }
        }
    }
    // 依赖检查
    if (needsDepCheck) {
        if (filteredPds == null) {
            filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
        }
        // 依赖检查,对应 depends-on 属性
        checkDependencies(beanName, mbd, filteredPds, pvs);
    }

    // 将属性应用到 bean 中
    if (pvs != null) {
        applyPropertyValues(beanName, mbd, bw, pvs);
    }
}

主要的逻辑:
1.根据 hasInstantiationAwareBeanPostProcessors 属性来判断是否需要在注入属性之前给 InstantiationAwareBeanPostProcessors 最后一次改变 bean 的机会,此过程可以控制 Spring 是否继续进行属性填充。
2.根据注入类型的不同来判断是根据名称来自动注入(autowireByName())还是根据类型来自动注入(autowireByType()),统一存入到 PropertyValues 中,PropertyValues 用于描述 bean 的属性。
3.判断是否需要进行 BeanPostProcessor 和 依赖检测。
4.将所有 PropertyValues 中的属性填充到 BeanWrapper 中。
第一步比较简单,这里就不详细介绍了

7.2.2.2.1 autowireByName

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

    // 对 Bean 对象中非简单属性
    String[] propertyNames = unsatisfiedNonSimpleProperties(mbd, bw);
    for (String propertyName : propertyNames) {
        // 如果容器中包含指定名称的 bean,则将该 bean 注入到 bean中
        if (containsBean(propertyName)) {
            // 递归获取相关 bean
            Object bean = getBean(propertyName);
            // 为指定名称的属性赋予属性值
            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 {
            if (logger.isTraceEnabled()) {
                logger.trace("Not autowiring property '" + propertyName + "' of bean '" + beanName +
                        "' by name: no matching bean found");
            }
        }
    }
}

7.2.2.2.2 autowireByType

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

    // 获取 TypeConverter 实例
    // 使用自定义的 TypeConverter,用于取代默认的 PropertyEditor 机制
    TypeConverter converter = getCustomTypeConverter();
    if (converter == null) {
        converter = bw;
    }

    Set autowiredBeanNames = new LinkedHashSet<>(4);
    // 获取非简单属性
    String[] propertyNames = unsatisfiedNonSimpleProperties(mbd, bw);
    for (String propertyName : propertyNames) {
        try {
            // 获取 PropertyDescriptor 实例
            PropertyDescriptor pd = bw.getPropertyDescriptor(propertyName);
            // 不要尝试按类型
            if (Object.class != pd.getPropertyType()) {
                // 探测指定属性的 set 方法
                MethodParameter methodParam = BeanUtils.getWriteMethodParameter(pd);
                boolean eager = !PriorityOrdered.class.isInstance(bw.getWrappedInstance());
                DependencyDescriptor desc = new AutowireByTypeDependencyDescriptor(methodParam, eager);
                // 解析指定 beanName 的属性所匹配的值,并把解析到的属性名称存储在 autowiredBeanNames 中
                // 当属性存在过个封装 bean 时将会找到所有匹配的 bean 并将其注入
                Object autowiredArgument = resolveDependency(desc, beanName, autowiredBeanNames, converter);
                if (autowiredArgument != null) {
                    pvs.add(propertyName, autowiredArgument);
                }
                // 迭代方式注入 bean
                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);
        }
    }
}

继续回到doCreateBean方法中

7.2.2.3 initializeBean

protected Object initializeBean(final String beanName, final Object bean, @Nullable RootBeanDefinition mbd) {
    if (System.getSecurityManager() != null) { // 安全模式
        AccessController.doPrivileged((PrivilegedAction) () -> {
            // 激活 Aware 方法,对特殊的 bean 处理:BeanNameAware、BeanClassLoaderAware、BeanFactoryAware
            invokeAwareMethods(beanName, bean);
            return null;
        }, getAccessControlContext());
    }
    else {
        invokeAwareMethods(beanName, bean);
    }

    // 后处理器,before
    Object wrappedBean = bean;
    if (mbd == null || !mbd.isSynthetic()) {
        wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
    }

    // 激活用户自定义的 init 方法
    try {
        invokeInitMethods(beanName, wrappedBean, mbd);
    }
    catch (Throwable ex) {
        throw new BeanCreationException(
                (mbd != null ? mbd.getResourceDescription() : null),
                beanName, "Invocation of init method failed", ex);
    }
    // 后处理器,after
    if (mbd == null || !mbd.isSynthetic()) {
        wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
    }

    return wrappedBean;
}

这里的前置处理和后置处理,就是执行BeanPostProcessor的postProcessBeforeInitialization和postProcessAfterInitialization方法,就是在这个地方,通过实现BeanPostProcessor接口从而实现了AOP功能,invokeInitMethods方法在下一篇文章中分析。

2.7.2.2.4 处理循环依赖

if (earlySingletonExposure) {
    Object earlySingletonReference = getSingleton(beanName, false);
    // 只有在存在循环依赖的情况下,earlySingletonReference 才不会为空
    if (earlySingletonReference != null) {
        // 如果 exposedObject 没有在初始化方法中被改变,也就是没有被增强
        if (exposedObject == bean) {
            exposedObject = earlySingletonReference;
        }
        // 处理依赖
        else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) {
            String[] dependentBeans = getDependentBeans(beanName);
            Set 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.");
            }
        }
    }
}

到此bean的创建过程就分析完成了

你可能感兴趣的:(bean加载三:bean创建)