方法执行流程图

doCreateBean.svg
doCreateBean.xmind
来到方法源码

  1. // 没有特殊情况下的创建对象
  2. try {
  3. Object beanInstance = doCreateBean(beanName, mbdToUse, args);
  4. if (logger.isTraceEnabled()) {
  5. logger.trace("Finished creating instance of bean '" + beanName + "'");
  6. }
  7. return beanInstance;
  8. }
  1. protected Object doCreateBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
  2. throws BeanCreationException {
  3. // Instantiate the bean.
  4. // instanceWrapper 拿着创建好的对象
  5. BeanWrapper instanceWrapper = null;
  6. if (mbd.isSingleton()) {
  7. // 第一次加载的话,缓存中没有该bean所以instanceWrapper仍然为null
  8. instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
  9. }
  10. if (instanceWrapper == null) {
  11. // 创建包装对象
  12. instanceWrapper = createBeanInstance(beanName, mbd, args);
  13. }
  14. // 创建包装对应的对象,此时属性全都是零值
  15. Object bean = instanceWrapper.getWrappedInstance();
  16. // 获取类对象
  17. Class<?> beanType = instanceWrapper.getWrappedClass();
  18. if (beanType != NullBean.class) {
  19. // 设置Class对象
  20. mbd.resolvedTargetType = beanType;
  21. }
  22. // Allow post-processors to modify the merged bean definition.
  23. synchronized (mbd.postProcessingLock) {
  24. if (!mbd.postProcessed) {
  25. try {
  26. // bean的后置处理器
  27. applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
  28. } catch (Throwable ex) {
  29. throw new BeanCreationException(mbd.getResourceDescription(), beanName,
  30. "Post-processing of merged bean definition failed", ex);
  31. }
  32. mbd.postProcessed = true;
  33. }
  34. }
  35. // Eagerly cache singletons to be able to resolve circular references
  36. // even when triggered by lifecycle interfaces like BeanFactoryAware.
  37. // 利用缓存处理循环依赖
  38. boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences &&
  39. isSingletonCurrentlyInCreation(beanName));
  40. if (earlySingletonExposure) {
  41. if (logger.isTraceEnabled()) {
  42. logger.trace("Eagerly caching bean '" + beanName +
  43. "' to allow for resolving potential circular references");
  44. }
  45. // !!! 单例 Bean 对象已经实例化,属性还没处理,可以通过引用找到堆上的这个对象
  46. // 将这个状态下的bean放到三级缓存中。表示可以从三级缓存中拿到这个已经创建但是还没有补充完属性的对象
  47. addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
  48. }
  49. // 初始化属性
  50. // Initialize the bean instance.
  51. Object exposedObject = bean;
  52. try {
  53. // 填充属性
  54. populateBean(beanName, mbd, instanceWrapper);
  55. // 初始化
  56. exposedObject = initializeBean(beanName, exposedObject, mbd);
  57. } catch (Throwable ex) {
  58. if (ex instanceof BeanCreationException && beanName.equals(((BeanCreationException) ex).getBeanName())) {
  59. throw (BeanCreationException) ex;
  60. } else {
  61. throw new BeanCreationException(
  62. mbd.getResourceDescription(), beanName, "Initialization of bean failed", ex);
  63. }
  64. }
  65. // 判断处理依赖引用
  66. if (earlySingletonExposure) {
  67. // 从缓存中获取bean
  68. Object earlySingletonReference = getSingleton(beanName, false);
  69. if (earlySingletonReference != null) {
  70. if (exposedObject == bean) {
  71. exposedObject = earlySingletonReference;
  72. // 判断是否有其他依赖的bean
  73. } else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) {
  74. String[] dependentBeans = getDependentBeans(beanName);
  75. Set<String> actualDependentBeans = new LinkedHashSet<>(dependentBeans.length);
  76. for (String dependentBean : dependentBeans) {
  77. if (!removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) {
  78. actualDependentBeans.add(dependentBean);
  79. }
  80. }
  81. // 如果依然有bean在创建中,异常
  82. if (!actualDependentBeans.isEmpty()) {
  83. throw new BeanCurrentlyInCreationException(beanName,
  84. "Bean with name '" + beanName + "' has been injected into other beans [" +
  85. StringUtils.collectionToCommaDelimitedString(actualDependentBeans) +
  86. "] in its raw version as part of a circular reference, but has eventually been " +
  87. "wrapped. This means that said other beans do not use the final version of the " +
  88. "bean. This is often the result of over-eager type matching - consider using " +
  89. "'getBeanNamesForType' with the 'allowEagerInit' flag turned off, for example.");
  90. }
  91. }
  92. }
  93. }
  94. // Register bean as disposable.
  95. try {
  96. // 注册销毁的方法
  97. registerDisposableBeanIfNecessary(beanName, bean, mbd);
  98. } catch (BeanDefinitionValidationException ex) {
  99. throw new BeanCreationException(
  100. mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex);
  101. }
  102. return exposedObject;
  103. }

创建 BeanWrapper

实例化对象,首先创建一个BeanWrapper对象,用来持有我们将要创建的对象,BeanWrapper 的父类继承关系如下:
image.png

接下来就到了bean的生命周期的环节。

创建对象实例

createBeanInstance

执行扩展处理器

  1. // Allow post-processors to modify the merged bean definition.
  2. synchronized (mbd.postProcessingLock) {
  3. if (!mbd.postProcessed) {
  4. try {
  5. // bean的后置处理器
  6. applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
  7. } catch (Throwable ex) {
  8. throw new BeanCreationException(mbd.getResourceDescription(), beanName,
  9. "Post-processing of merged bean definition failed", ex);
  10. }
  11. mbd.postProcessed = true;
  12. }
  13. }

加入三级缓存

实例化对象后,目前该 bean 的状态:

  1. 单例 bean 对象已经实例化,属性还没处理
  2. 将这个状态下的bean放到三级缓存singletonFactories中
  3. 该bean可以从三级缓存中拿到,通过引用可以找到堆上的这个对象

    1. // 是否需要提前曝光条件:1.单例 2.允许循环以来 3.bean正在创建中
    2. boolean earlySingletonExposure = (mbd.isSingleton()
    3. && this.allowCircularReferences
    4. && isSingletonCurrentlyInCreation(beanName));
    5. if (earlySingletonExposure) {
    6. if (logger.isTraceEnabled()) {
    7. logger.trace("Eagerly caching bean '" + beanName + "'
    8. to allow for resolving potential circular references");
    9. }
    10. /*
    11. 为避免后期循环依赖,可以在bean初始化完成前将创建实例的 ObjectFactory 加入工厂缓存
    12. 到这里↓
    13. 1.单例bean对象已经实例化,属性还没处理
    14. 2.将这个状态下的bean放到三级缓存singletonFactories中
    15. 3.该bean可以从三级缓存中拿到,通过引用可以找到堆上的这个对象
    16. // 其中我们熟知的AoP就是在这里将 advice 动态织入bean中,若没有则直接返回 bean,不做任何处理
    17. */
    18. addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
    19. }

进入方法 addSingletonFactory。该方法的第二个参数是一个接口:

  1. protected void addSingletonFactory(String beanName, ObjectFactory<?> singletonFactory) {
  2. Assert.notNull(singletonFactory, "Singleton factory must not be null");
  3. synchronized (this.singletonObjects) {
  4. if (!this.singletonObjects.containsKey(beanName)) {
  5. this.singletonFactories.put(beanName, singletonFactory);
  6. this.earlySingletonObjects.remove(beanName);
  7. this.registeredSingletons.add(beanName);
  8. }
  9. }
  10. }

该方法的第二个参数是一个函数式接口:

  1. @FunctionalInterface
  2. public interface ObjectFactory<T> {
  3. T getObject() throws BeansException;
  4. }

AbstractAutowireCapableBeanFactory 中匿名内部类的形式用 getEarlyBeanReference 实现了该接口。

  1. protected Object getEarlyBeanReference(String beanName, RootBeanDefinition mbd, Object bean) {
  2. Object exposedObject = bean;
  3. if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
  4. for (BeanPostProcessor bp : getBeanPostProcessors()) {
  5. if (bp instanceof SmartInstantiationAwareBeanPostProcessor) {
  6. SmartInstantiationAwareBeanPostProcessor ibp = (SmartInstantiationAwareBeanPostProcessor) bp;
  7. exposedObject = ibp.getEarlyBeanReference(exposedObject, beanName);
  8. }
  9. }
  10. }
  11. return exposedObject;
  12. }

填充属性

populateBean

初始化对象

initializeBean

检测循环依赖

  1. if (earlySingletonExposure) {
  2. // 从缓存中获取bean
  3. Object earlySingletonReference = getSingleton(beanName, false);
  4. // 检测到循环依赖的情况下不为空
  5. if (earlySingletonReference != null) {
  6. // 如果exposedObject 没有在初始化方法中被改变,说明没有被增强
  7. if (exposedObject == bean) {
  8. exposedObject = earlySingletonReference;
  9. } else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) {
  10. String[] dependentBeans = getDependentBeans(beanName);
  11. Set<String> actualDependentBeans = new LinkedHashSet<>(dependentBeans.length);
  12. for (String dependentBean : dependentBeans) {
  13. // 检测依赖
  14. if (!removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) {
  15. actualDependentBeans.add(dependentBean);
  16. }
  17. }
  18. // actualDependentBeans不为空异常
  19. /*
  20. 因为bean创建好了,那么它依赖的bean应该都已经创建好了。
  21. 如果actualDependentBeans不为空表示依赖的bean并没有完全创建好。
  22. */
  23. if (!actualDependentBeans.isEmpty()) {
  24. throw new BeanCurrentlyInCreationException(beanName,
  25. "Bean with name '" + beanName + "' has been injected into other beans [" +
  26. StringUtils.collectionToCommaDelimitedString(actualDependentBeans) +
  27. "] in its raw version as part of a circular reference, but has eventually been " +
  28. "wrapped. This means that said other beans do not use the final version of the " +
  29. "bean. This is often the result of over-eager type matching - consider using " +
  30. "'getBeanNamesForType' with the 'allowEagerInit' flag turned off, for example.");
  31. }
  32. }
  33. }
  34. }

注册销毁方法

  1. // Register bean as disposable.
  2. try {
  3. // 注册销毁的方法
  4. registerDisposableBeanIfNecessary(beanName, bean, mbd);
  5. } catch (BeanDefinitionValidationException ex) {
  6. throw new BeanCreationException(
  7. mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex);
  8. }