1. Object person = xmlBeanFactory.getBean("person");
  2. AbstractBeanFactory.class
  3. @Override
  4. public Object getBean(String name) throws BeansException {
  5. return doGetBean(name, null, null, false);
  6. }
  1. @SuppressWarnings("unchecked")
  2. protected <T> T doGetBean(
  3. String name, @Nullable Class<T> requiredType, @Nullable Object[] args, boolean typeCheckOnly)
  4. throws BeansException {
  5. //1.转换为beanName
  6. String beanName = transformedBeanName(name);
  7. Object beanInstance;
  8. //2.从三级缓存中获取
  9. Object sharedInstance = getSingleton(beanName);
  10. //获取到了
  11. if (sharedInstance != null && args == null) {
  12. if (logger.isTraceEnabled()) {
  13. //3.是否是循环依赖
  14. if (isSingletonCurrentlyInCreation(beanName)) {
  15. logger.trace("Returning eagerly cached instance of singleton bean '" + beanName +
  16. "' that is not fully initialized yet - a consequence of a circular reference");
  17. }
  18. else {
  19. logger.trace("Returning cached instance of singleton bean '" + beanName + "'");
  20. }
  21. }
  22. //获取Bean实例
  23. beanInstance = getObjectForBeanInstance(sharedInstance, name, beanName, null);
  24. }
  25. else {
  26. // Fail if we're already creating this bean instance:
  27. // We're assumably within a circular reference.
  28. //若缓存中没有,且是一个 原型的循环依赖时 抛出异常
  29. if (isPrototypeCurrentlyInCreation(beanName)) {
  30. throw new BeanCurrentlyInCreationException(beanName);
  31. }
  32. //获取父级的BeanFactory
  33. BeanFactory parentBeanFactory = getParentBeanFactory();
  34. //若父级不为空,且此容器没有beanName的BeanDefinition定义进入
  35. if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
  36. // Not found -> check parent. 最初的beanname
  37. String nameToLookup = originalBeanName(name);
  38. if (parentBeanFactory instanceof AbstractBeanFactory) {
  39. return ((AbstractBeanFactory) parentBeanFactory).doGetBean(
  40. nameToLookup, requiredType, args, typeCheckOnly);
  41. }
  42. else if (args != null) {
  43. // Delegation to parent with explicit args.
  44. return (T) parentBeanFactory.getBean(nameToLookup, args);
  45. }
  46. else if (requiredType != null) {
  47. // No args -> delegate to standard getBean method.
  48. return parentBeanFactory.getBean(nameToLookup, requiredType);
  49. }
  50. else {
  51. return (T) parentBeanFactory.getBean(nameToLookup);
  52. }
  53. //..........
  54. }
  55. //从父级那边获取元素
  56. if (!typeCheckOnly) {
  57. //标记Bean已经被创建
  58. markBeanAsCreated(beanName);
  59. }
  60. StartupStep beanCreation = this.applicationStartup.start("spring.beans.instantiate")
  61. .tag("beanName", name);
  62. try {
  63. if (requiredType != null) {
  64. beanCreation.tag("beanType", requiredType::toString);
  65. }
  66. //转换为 RootBeanDefinition
  67. RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
  68. checkMergedBeanDefinition(mbd, beanName, args);
  69. // 先get依赖的类
  70. String[] dependsOn = mbd.getDependsOn();
  71. if (dependsOn != null) {
  72. for (String dep : dependsOn) {
  73. //若互相依赖则抛异常
  74. if (isDependent(beanName, dep)) {
  75. throw new BeanCreationException(mbd.getResourceDescription(), beanName,
  76. "Circular depends-on relationship between '" + beanName + "' and '" + dep + "'");
  77. }
  78. //
  79. registerDependentBean(dep, beanName);
  80. try {
  81. //先构造dep依赖
  82. getBean(dep);
  83. }
  84. catch (NoSuchBeanDefinitionException ex) {
  85. throw new BeanCreationException(mbd.getResourceDescription(), beanName,
  86. "'" + beanName + "' depends on missing bean '" + dep + "'", ex);
  87. }
  88. }
  89. }
  90. // Create bean instance.
  91. if (mbd.isSingleton()) {
  92. //若是单例模式 beanName 和 lamda
  93. sharedInstance = getSingleton(beanName, () -> {
  94. try {
  95. return createBean(beanName, mbd, args);
  96. }
  97. catch (BeansException ex) {
  98. // Explicitly remove instance from singleton cache: It might have been put there
  99. // eagerly by the creation process, to allow for circular reference resolution.
  100. // Also remove any beans that received a temporary reference to the bean.
  101. destroySingleton(beanName);
  102. throw ex;
  103. }
  104. });
  105. //
  106. beanInstance = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
  107. }
  108. else if (mbd.isPrototype()) {
  109. //r若是原型Bean
  110. Object prototypeInstance = null;
  111. try {
  112. beforePrototypeCreation(beanName);
  113. prototypeInstance = createBean(beanName, mbd, args);
  114. }
  115. finally {
  116. afterPrototypeCreation(beanName);
  117. }
  118. beanInstance = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);
  119. }
  120. else {
  121. //其他的Scope
  122. String scopeName = mbd.getScope();
  123. if (!StringUtils.hasLength(scopeName)) {
  124. throw new IllegalStateException("No scope name defined for bean ´" + beanName + "'");
  125. }
  126. Scope scope = this.scopes.get(scopeName);
  127. if (scope == null) {
  128. throw new IllegalStateException("No Scope registered for scope name '" + scopeName + "'");
  129. }
  130. try {
  131. Object scopedInstance = scope.get(beanName, () -> {
  132. beforePrototypeCreation(beanName);
  133. try {
  134. return createBean(beanName, mbd, args);
  135. }
  136. finally {
  137. afterPrototypeCreation(beanName);
  138. }
  139. });
  140. beanInstance = getObjectForBeanInstance(scopedInstance, name, beanName, mbd);
  141. }
  142. catch (IllegalStateException ex) {
  143. throw new ScopeNotActiveException(beanName, scopeName, ex);
  144. }
  145. }
  146. }
  147. catch (BeansException ex) {
  148. beanCreation.tag("exception", ex.getClass().toString());
  149. beanCreation.tag("message", String.valueOf(ex.getMessage()));
  150. cleanupAfterBeanCreationFailure(beanName);
  151. throw ex;
  152. }
  153. finally {
  154. beanCreation.end();
  155. }
  156. }
  157. return adaptBeanInstance(name, beanInstance, requiredType);
  158. }

1.转换成对应的beanName

  1. 对于"&xxx"这种的的,是去除&
  2. 对于一些别名的传入,会转换为beanName ```java protected String transformedBeanName(String name) {
    1. return canonicalName(BeanFactoryUtils.transformedBeanName(name));
    }

// BeanFactoryUtils.transformedBeanName(name) public static String transformedBeanName(String name) { //name不可为空 Assert.notNull(name, “‘name’ must not be null”); if (!name.startsWith(BeanFactory.FACTORY_BEAN_PREFIX)) { //若不是 &开头返回即可 return name; } //若这个name不存在,则将这个name取去除&符号的name 将其作为 &xxx->xxx存入map中 return transformedBeanNameCache.computeIfAbsent(name, beanName -> { do { beanName = beanName.substring(BeanFactory.FACTORY_BEAN_PREFIX.length()); } while (beanName.startsWith(BeanFactory.FACTORY_BEAN_PREFIX)); return beanName; }); }

//SimpleAliasRegistry.class中的方法将别名转换为beanName //aliasMap就是 alia->beanName public String canonicalName(String name) { String canonicalName = name; // Handle aliasing… String resolvedName; do { resolvedName = this.aliasMap.get(canonicalName); if (resolvedName != null) { canonicalName = resolvedName; } } while (resolvedName != null); return canonicalName; }

  1. <a name="CoAqt"></a>
  2. # 2.尝试从缓存中加载单例
  3. 这里的缓存就是传说中的3级缓存,来自`DefaultSingletonBeanRegistry`类中的三级缓存
  4. ```java
  5. @Nullable
  6. protected Object getSingleton(String beanName, boolean allowEarlyReference) {
  7. // 快速的从单例对象缓存(一级缓存)获取对象且不加锁
  8. Object singletonObject = this.singletonObjects.get(beanName);
  9. //单例对象获取不到且 正在被创建才会进入
  10. if (singletonObject == null && isSingletonCurrentlyInCreation(beanName)) {
  11. //从早期对象中获取
  12. singletonObject = this.earlySingletonObjects.get(beanName);
  13. //早期对象还是没有
  14. if (singletonObject == null && allowEarlyReference) {
  15. //对单例对象进行加锁
  16. synchronized (this.singletonObjects) {
  17. //DCL
  18. singletonObject = this.singletonObjects.get(beanName);
  19. //确实没有
  20. if (singletonObject == null) {
  21. //再从二级缓存获取
  22. singletonObject = this.earlySingletonObjects.get(beanName);
  23. if (singletonObject == null) {
  24. ObjectFactory<?> singletonFactory = this.singletonFactories.get(beanName);
  25. //三级缓存中有 ObjectFactory
  26. if (singletonFactory != null) {
  27. //执行构建
  28. singletonObject = singletonFactory.getObject();
  29. this.earlySingletonObjects.put(beanName, singletonObject);
  30. this.singletonFactories.remove(beanName);
  31. }
  32. }
  33. }
  34. }
  35. }
  36. }
  37. return singletonObject;
  38. }
  1. 整体代码就是一个DCL,第一遍检查一、二级缓存到底有无bean、加锁后再次检查一遍
  2. 判断是否bean正在被创建时 ```java //这样的Set就是一个线程安全的 里面放入正在创建啊的beanName private final Set singletonsCurrentlyInCreation =
    1. Collections.newSetFromMap(new ConcurrentHashMap<>(16));
  1. //代码简单
  2. public boolean isSingletonCurrentlyInCreation(String beanName) {
  3. return this.singletonsCurrentlyInCreation.contains(beanName);
  4. }
  1. 3. `allowEarlyReference`参数是调用时传入,代表是否允许引用早期Bean对象
  2. 4. `ObjectFactory<>`是一个函数式接口,也就是说三级缓存时beanName->getObjectlamda表达式
  3. ```java
  4. @FunctionalInterface
  5. public interface ObjectFactory<T> {
  6. /**
  7. * Return an instance (possibly shared or independent)
  8. * of the object managed by this factory.
  9. * @return the resulting instance
  10. * @throws BeansException in case of creation errors
  11. */
  12. T getObject() throws BeansException;
  13. }

3.bean的实例化

  1. if (sharedInstance != null && args == null) {
  2. if (logger.isTraceEnabled()) {
  3. if (isSingletonCurrentlyInCreation(beanName)) {
  4. logger.trace("Returning eagerly cached instance of singleton bean '" + beanName +
  5. "' that is not fully initialized yet - a consequence of a circular reference");
  6. }
  7. else {
  8. logger.trace("Returning cached instance of singleton bean '" + beanName + "'");
  9. }
  10. }
  11. beanInstance = getObjectForBeanInstance(sharedInstance, name, beanName, null);
  12. }
  13. else {
  14. //....
  15. }

若从三级缓存中获取了实例

  1. /**
  2. * 要么就是bean实例自己
  3. * 要么就是FactoryBean创建的对象
  4. *
  5. */
  6. protected Object getObjectForBeanInstance(
  7. Object beanInstance, String name, String beanName, @Nullable RootBeanDefinition mbd) {
  8. // 若name是对FactoryBean的应用则 返回beanInstance
  9. if (BeanFactoryUtils.isFactoryDereference(name)) {
  10. if (beanInstance instanceof NullBean) {
  11. return beanInstance;
  12. }
  13. if (!(beanInstance instanceof FactoryBean)) {
  14. throw new BeanIsNotAFactoryException(beanName, beanInstance.getClass());
  15. }
  16. if (mbd != null) {
  17. mbd.isFactoryBean = true;
  18. }
  19. return beanInstance;
  20. }
  21. // 若不是Factorybean直接返回
  22. if (!(beanInstance instanceof FactoryBean)) {
  23. return beanInstance;
  24. }
  25. Object object = null;
  26. if (mbd != null) {
  27. mbd.isFactoryBean = true;
  28. }
  29. else {
  30. //从这个Map factoryBeanObjectCache中获取内容, beanName->getObject()
  31. object = getCachedObjectForFactoryBean(beanName);
  32. }
  33. if (object == null) {
  34. // Return bean instance from factory.
  35. FactoryBean<?> factory = (FactoryBean<?>) beanInstance;
  36. // Caches object obtained from FactoryBean if it is a singleton.
  37. if (mbd == null && containsBeanDefinition(beanName)) {
  38. mbd = getMergedLocalBeanDefinition(beanName);
  39. }
  40. boolean synthetic = (mbd != null && mbd.isSynthetic());
  41. object = getObjectFromFactoryBean(factory, beanName, !synthetic);
  42. }
  43. return object;
  44. }
  1. protected Object getObjectFromFactoryBean(FactoryBean<?> factory, String beanName, boolean shouldPostProcess) {
  2. if (factory.isSingleton() && containsSingleton(beanName)) {
  3. //如果是单例且 FactoryBean已经创建出来了
  4. synchronized (getSingletonMutex()) {
  5. //还是先尝试从 factoryBeanObjectCache中获取 bean
  6. Object object = this.factoryBeanObjectCache.get(beanName);
  7. if (object == null) {
  8. //没有的话就doGet
  9. object = doGetObjectFromFactoryBean(factory, beanName);
  10. // Only post-process and store if not put there already during getObject() call above
  11. // (e.g. because of circular reference processing triggered by custom getBean calls)
  12. //这里会从缓存中再尝试获取一次
  13. Object alreadyThere = this.factoryBeanObjectCache.get(beanName);
  14. if (alreadyThere != null) {
  15. object = alreadyThere;
  16. }
  17. else {
  18. if (shouldPostProcess) {
  19. //若 beanname正在创建,则直接返回object
  20. if (isSingletonCurrentlyInCreation(beanName)) {
  21. // Temporarily return non-post-processed object, not storing it yet..
  22. //这是一个没有走后置逻辑的object
  23. return object;
  24. }
  25. //将beanName设置为正在创建
  26. beforeSingletonCreation(beanName);
  27. try {
  28. //执行postProcessAfterInitialization
  29. object = postProcessObjectFromFactoryBean(object, beanName);
  30. }
  31. catch (Throwable ex) {
  32. throw new BeanCreationException(beanName,
  33. "Post-processing of FactoryBean's singleton object failed", ex);
  34. }
  35. finally {
  36. //从正在创建的bean中移出
  37. afterSingletonCreation(beanName);
  38. }
  39. }
  40. if (containsSingleton(beanName)) {
  41. //若进入了一级缓存则, factoryBean也缓存一份
  42. this.factoryBeanObjectCache.put(beanName, object);
  43. }
  44. }
  45. }
  46. return object;
  47. }
  48. }
  49. else {
  50. //若不是单例FactoyBean,直接重新获取FactoryBean ,.getObject
  51. Object object = doGetObjectFromFactoryBean(factory, beanName);
  52. if (shouldPostProcess) {
  53. try {
  54. object = postProcessObjectFromFactoryBean(object, beanName);
  55. }
  56. catch (Throwable ex) {
  57. throw new BeanCreationException(beanName, "Post-processing of FactoryBean's object failed", ex);
  58. }
  59. }
  60. return object;
  61. }
  62. }
  1. private Object doGetObjectFromFactoryBean(FactoryBean<?> factory, String beanName) throws BeanCreationException {
  2. Object object;
  3. try {
  4. if (System.getSecurityManager() != null) {
  5. AccessControlContext acc = getAccessControlContext();
  6. try {
  7. object = AccessController.doPrivileged((PrivilegedExceptionAction<Object>) factory::getObject, acc);
  8. }
  9. catch (PrivilegedActionException pae) {
  10. throw pae.getException();
  11. }
  12. }
  13. else {
  14. //调用getObject方法
  15. object = factory.getObject();
  16. }
  17. }
  18. catch (FactoryBeanNotInitializedException ex) {
  19. throw new BeanCurrentlyInCreationException(beanName, ex.toString());
  20. }
  21. catch (Throwable ex) {
  22. throw new BeanCreationException(beanName, "FactoryBean threw exception on object creation", ex);
  23. }
  24. // Do not accept a null value for a FactoryBean that's not fully
  25. // initialized yet: Many FactoryBeans just return null then.
  26. if (object == null) {
  27. if (isSingletonCurrentlyInCreation(beanName)) {
  28. throw new BeanCurrentlyInCreationException(
  29. beanName, "FactoryBean which is currently in creation returned null from getObject");
  30. }
  31. object = new NullBean();
  32. }
  33. return object;
  34. }

以上是bean在三级缓存中可以取到内容的情况,下面我们来看一下else分支

这段代码就是下面的4~8的一个大概流程

  1. if (sharedInstance != null && args == null) {
  2. //三级缓存中可以取到的场景
  3. }
  4. else {
  5. // Fail if we're already creating this bean instance:
  6. // We're assumably within a circular reference.
  7. //若是原型模式正在创建,则直接抛出异常
  8. if (isPrototypeCurrentlyInCreation(beanName)) {
  9. throw new BeanCurrentlyInCreationException(beanName);
  10. }
  11. // 获取父Beanfactory
  12. BeanFactory parentBeanFactory = getParentBeanFactory();
  13. //若自己没有这个BeanDefinition
  14. if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
  15. // Not found -> check parent.
  16. String nameToLookup = originalBeanName(name);
  17. if (parentBeanFactory instanceof AbstractBeanFactory) {
  18. return ((AbstractBeanFactory) parentBeanFactory).doGetBean(
  19. nameToLookup, requiredType, args, typeCheckOnly);
  20. }
  21. else if (args != null) {
  22. // Delegation to parent with explicit args.
  23. return (T) parentBeanFactory.getBean(nameToLookup, args);
  24. }
  25. else if (requiredType != null) {
  26. // No args -> delegate to standard getBean method.
  27. return parentBeanFactory.getBean(nameToLookup, requiredType);
  28. }
  29. else {
  30. return (T) parentBeanFactory.getBean(nameToLookup);
  31. }
  32. }
  33. //标记bean被创建
  34. if (!typeCheckOnly) {
  35. markBeanAsCreated(beanName);
  36. }
  37. StartupStep beanCreation = this.applicationStartup.start("spring.beans.instantiate")
  38. .tag("beanName", name);
  39. try {
  40. if (requiredType != null) {
  41. beanCreation.tag("beanType", requiredType::toString);
  42. }
  43. // 获取BeanDefinition
  44. RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
  45. checkMergedBeanDefinition(mbd, beanName, args);
  46. // Guarantee initialization of beans that the current bean depends on. //保证没有循环的depend-on
  47. String[] dependsOn = mbd.getDependsOn();
  48. if (dependsOn != null) {
  49. for (String dep : dependsOn) {
  50. if (isDependent(beanName, dep)) {
  51. throw new BeanCreationException(mbd.getResourceDescription(), beanName,
  52. "Circular depends-on relationship between '" + beanName + "' and '" + dep + "'");
  53. }
  54. //注册 被依赖的 bean
  55. registerDependentBean(dep, beanName);
  56. try {
  57. //getBean depend-on
  58. getBean(dep);
  59. }
  60. catch (NoSuchBeanDefinitionException ex) {
  61. throw new BeanCreationException(mbd.getResourceDescription(), beanName,
  62. "'" + beanName + "' depends on missing bean '" + dep + "'", ex);
  63. }
  64. }
  65. }
  66. // Create bean instance.
  67. if (mbd.isSingleton()) {
  68. //若是单例模式 ,rgetSinleton 并放入 beanName->ObjectFactory表达式
  69. sharedInstance = getSingleton(beanName, () -> {
  70. try {
  71. return createBean(beanName, mbd, args);
  72. }
  73. catch (BeansException ex) {
  74. // Explicitly remove instance from singleton cache: It might have been put there
  75. // eagerly by the creation process, to allow for circular reference resolution.
  76. // Also remove any beans that received a temporary reference to the bean.
  77. destroySingleton(beanName);
  78. throw ex;
  79. }
  80. });
  81. beanInstance = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
  82. }
  83. else if (mbd.isPrototype()) {
  84. // It's a prototype -> create a new instance.
  85. Object prototypeInstance = null;
  86. try {
  87. beforePrototypeCreation(beanName);
  88. prototypeInstance = createBean(beanName, mbd, args);
  89. }
  90. finally {
  91. afterPrototypeCreation(beanName);
  92. }
  93. beanInstance = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);
  94. }
  95. else {
  96. String scopeName = mbd.getScope();
  97. if (!StringUtils.hasLength(scopeName)) {
  98. throw new IllegalStateException("No scope name defined for bean ´" + beanName + "'");
  99. }
  100. Scope scope = this.scopes.get(scopeName);
  101. if (scope == null) {
  102. throw new IllegalStateException("No Scope registered for scope name '" + scopeName + "'");
  103. }
  104. try {
  105. Object scopedInstance = scope.get(beanName, () -> {
  106. beforePrototypeCreation(beanName);
  107. try {
  108. return createBean(beanName, mbd, args);
  109. }
  110. finally {
  111. afterPrototypeCreation(beanName);
  112. }
  113. });
  114. beanInstance = getObjectForBeanInstance(scopedInstance, name, beanName, mbd);
  115. }
  116. catch (IllegalStateException ex) {
  117. throw new ScopeNotActiveException(beanName, scopeName, ex);
  118. }
  119. }
  120. }
  121. catch (BeansException ex) {
  122. beanCreation.tag("exception", ex.getClass().toString());
  123. beanCreation.tag("message", String.valueOf(ex.getMessage()));
  124. cleanupAfterBeanCreationFailure(beanName);
  125. throw ex;
  126. }
  127. finally {
  128. beanCreation.end();
  129. }
  130. }
  131. return adaptBeanInstance(name, beanInstance, requiredType);
  1. @SuppressWarnings("unchecked")
  2. <T> T adaptBeanInstance(String name, Object bean, @Nullable Class<?> requiredType) {
  3. // Check if required type matches the type of the actual bean instance.
  4. if (requiredType != null && !requiredType.isInstance(bean)) {
  5. try {
  6. Object convertedBean = getTypeConverter().convertIfNecessary(bean, requiredType);
  7. if (convertedBean == null) {
  8. throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
  9. }
  10. return (T) convertedBean;
  11. }
  12. catch (TypeMismatchException ex) {
  13. if (logger.isTraceEnabled()) {
  14. logger.trace("Failed to convert bean '" + name + "' to required type '" +
  15. ClassUtils.getQualifiedName(requiredType) + "'", ex);
  16. }
  17. throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
  18. }
  19. }
  20. return (T) bean;
  21. }

4.原型模式的依赖检查

  1. public Object getSingleton(String beanName, ObjectFactory<?> singletonFactory) {
  2. Assert.notNull(beanName, "Bean name must not be null");
  3. synchronized (this.singletonObjects) {
  4. Object singletonObject = this.singletonObjects.get(beanName);
  5. if (singletonObject == null) {
  6. if (this.singletonsCurrentlyInDestruction) {
  7. throw new BeanCreationNotAllowedException(beanName,
  8. "Singleton bean creation not allowed while singletons of this factory are in destruction " +
  9. "(Do not request a bean from a BeanFactory in a destroy method implementation!)");
  10. }
  11. if (logger.isDebugEnabled()) {
  12. logger.debug("Creating shared instance of singleton bean '" + beanName + "'");
  13. }
  14. beforeSingletonCreation(beanName);
  15. boolean newSingleton = false;
  16. boolean recordSuppressedExceptions = (this.suppressedExceptions == null);
  17. if (recordSuppressedExceptions) {
  18. this.suppressedExceptions = new LinkedHashSet<>();
  19. }
  20. try {
  21. //最后会条这里,执行lamda表达式 见图
  22. singletonObject = singletonFactory.getObject();
  23. newSingleton = true;
  24. }
  25. catch (IllegalStateException ex) {
  26. // Has the singleton object implicitly appeared in the meantime ->
  27. // if yes, proceed with it since the exception indicates that state.
  28. singletonObject = this.singletonObjects.get(beanName);
  29. if (singletonObject == null) {
  30. throw ex;
  31. }
  32. }
  33. catch (BeanCreationException ex) {
  34. if (recordSuppressedExceptions) {
  35. for (Exception suppressedException : this.suppressedExceptions) {
  36. ex.addRelatedCause(suppressedException);
  37. }
  38. }
  39. throw ex;
  40. }
  41. finally {
  42. if (recordSuppressedExceptions) {
  43. this.suppressedExceptions = null;
  44. }
  45. afterSingletonCreation(beanName);
  46. }
  47. if (newSingleton) {
  48. //若是新单例还会 放入 三级缓存
  49. addSingleton(beanName, singletonObject);
  50. }
  51. }
  52. return singletonObject;
  53. }
  54. }

image.png

  1. @Override
  2. protected Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
  3. throws BeanCreationException {
  4. if (logger.isTraceEnabled()) {
  5. logger.trace("Creating instance of bean '" + beanName + "'");
  6. }
  7. RootBeanDefinition mbdToUse = mbd;
  8. // Make sure bean class is actually resolved at this point, and
  9. // clone the bean definition in case of a dynamically resolved Class
  10. // which cannot be stored in the shared merged bean definition.
  11. Class<?> resolvedClass = resolveBeanClass(mbd, beanName);
  12. if (resolvedClass != null && !mbd.hasBeanClass() && mbd.getBeanClassName() != null) {
  13. mbdToUse = new RootBeanDefinition(mbd);
  14. mbdToUse.setBeanClass(resolvedClass);
  15. }
  16. // Prepare method overrides.
  17. try {
  18. mbdToUse.prepareMethodOverrides();
  19. }
  20. catch (BeanDefinitionValidationException ex) {
  21. throw new BeanDefinitionStoreException(mbdToUse.getResourceDescription(),
  22. beanName, "Validation of method overrides failed", ex);
  23. }
  24. try {
  25. // Give BeanPostProcessors a chance to return a proxy instead of the target bean instance.
  26. Object bean = resolveBeforeInstantiation(beanName, mbdToUse);
  27. if (bean != null) {
  28. return bean;
  29. }
  30. }
  31. catch (Throwable ex) {
  32. throw new BeanCreationException(mbdToUse.getResourceDescription(), beanName,
  33. "BeanPostProcessor before instantiation of bean failed", ex);
  34. }
  35. try {
  36. //到doCreateBean
  37. Object beanInstance = doCreateBean(beanName, mbdToUse, args);
  38. if (logger.isTraceEnabled()) {
  39. logger.trace("Finished creating instance of bean '" + beanName + "'");
  40. }
  41. return beanInstance;
  42. }
  43. catch (BeanCreationException | ImplicitlyAppearedSingletonException ex) {
  44. // A previously detected exception with proper bean creation context already,
  45. // or illegal singleton state to be communicated up to DefaultSingletonBeanRegistry.
  46. throw ex;
  47. }
  48. catch (Throwable ex) {
  49. throw new BeanCreationException(
  50. mbdToUse.getResourceDescription(), beanName, "Unexpected exception during bean creation", ex);
  51. }
  52. }
  1. protected Object doCreateBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
  2. throws BeanCreationException {
  3. // Instantiate the bean.
  4. BeanWrapper instanceWrapper = null;
  5. if (mbd.isSingleton()) {
  6. instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
  7. }
  8. if (instanceWrapper == null) {
  9. //创建Bean实例
  10. instanceWrapper = createBeanInstance(beanName, mbd, args);
  11. }
  12. Object bean = instanceWrapper.getWrappedInstance();
  13. Class<?> beanType = instanceWrapper.getWrappedClass();
  14. if (beanType != NullBean.class) {
  15. mbd.resolvedTargetType = beanType;
  16. }
  17. // Allow post-processors to modify the merged bean definition.
  18. synchronized (mbd.postProcessingLock) {
  19. if (!mbd.postProcessed) {
  20. try {
  21. //应用BeanMergedBeanDefinitionPostProcessor
  22. applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
  23. }
  24. catch (Throwable ex) {
  25. throw new BeanCreationException(mbd.getResourceDescription(), beanName,
  26. "Post-processing of merged bean definition failed", ex);
  27. }
  28. mbd.postProcessed = true;
  29. }
  30. }
  31. // Eagerly cache singletons to be able to resolve circular references
  32. // even when triggered by lifecycle interfaces like BeanFactoryAware.
  33. boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences &&
  34. isSingletonCurrentlyInCreation(beanName));
  35. if (earlySingletonExposure) {
  36. if (logger.isTraceEnabled()) {
  37. logger.trace("Eagerly caching bean '" + beanName +
  38. "' to allow for resolving potential circular references");
  39. }
  40. //放入三级缓存解决循环依赖
  41. addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
  42. }
  43. // Initialize the bean instance.
  44. Object exposedObject = bean;
  45. try {
  46. //填充bean的属性
  47. populateBean(beanName, mbd, instanceWrapper);
  48. exposedObject = initializeBean(beanName, exposedObject, mbd);
  49. }
  50. catch (Throwable ex) {
  51. if (ex instanceof BeanCreationException && beanName.equals(((BeanCreationException) ex).getBeanName())) {
  52. throw (BeanCreationException) ex;
  53. }
  54. else {
  55. throw new BeanCreationException(
  56. mbd.getResourceDescription(), beanName, "Initialization of bean failed", ex);
  57. }
  58. }
  59. //若是二级缓存引用, 需要判断
  60. if (earlySingletonExposure) {
  61. Object earlySingletonReference = getSingleton(beanName, false);
  62. if (earlySingletonReference != null) {
  63. //exporsedObject在一波 populate后任 和 实例化时的对象是同一个
  64. if (exposedObject == bean) {
  65. exposedObject = earlySingletonReference;
  66. }
  67. else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) {
  68. String[] dependentBeans = getDependentBeans(beanName);
  69. Set<String> actualDependentBeans = new LinkedHashSet<>(dependentBeans.length);
  70. for (String dependentBean : dependentBeans) {
  71. if (!removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) {
  72. actualDependentBeans.add(dependentBean);
  73. }
  74. }
  75. if (!actualDependentBeans.isEmpty()) {
  76. throw new BeanCurrentlyInCreationException(beanName,
  77. "Bean with name '" + beanName + "' has been injected into other beans [" +
  78. StringUtils.collectionToCommaDelimitedString(actualDependentBeans) +
  79. "] in its raw version as part of a circular reference, but has eventually been " +
  80. "wrapped. This means that said other beans do not use the final version of the " +
  81. "bean. This is often the result of over-eager type matching - consider using " +
  82. "'getBeanNamesForType' with the 'allowEagerInit' flag turned off, for example.");
  83. }
  84. }
  85. }
  86. }
  87. // Register bean as disposable.
  88. try {
  89. //注册 Disposable
  90. registerDisposableBeanIfNecessary(beanName, bean, mbd);
  91. }
  92. catch (BeanDefinitionValidationException ex) {
  93. throw new BeanCreationException(
  94. mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex);
  95. }
  96. return exposedObject;
  97. }
  1. protected void populateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw) {
  2. if (bw == null) {
  3. if (mbd.hasPropertyValues()) {
  4. throw new BeanCreationException(
  5. mbd.getResourceDescription(), beanName, "Cannot apply property values to null instance");
  6. }
  7. else {
  8. // Skip property population phase for null instance.
  9. return;
  10. }
  11. }
  12. // Give any InstantiationAwareBeanPostProcessors the opportunity to modify the
  13. // state of the bean before properties are set. This can be used, for example,
  14. // to support styles of field injection.
  15. if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
  16. for (InstantiationAwareBeanPostProcessor bp : getBeanPostProcessorCache().instantiationAware) {
  17. if (!bp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {
  18. return;
  19. }
  20. }
  21. }
  22. PropertyValues pvs = (mbd.hasPropertyValues() ? mbd.getPropertyValues() : null);
  23. //进行了自动装配
  24. int resolvedAutowireMode = mbd.getResolvedAutowireMode();
  25. if (resolvedAutowireMode == AUTOWIRE_BY_NAME || resolvedAutowireMode == AUTOWIRE_BY_TYPE) {
  26. MutablePropertyValues newPvs = new MutablePropertyValues(pvs);
  27. // Add property values based on autowire by name if applicable.
  28. if (resolvedAutowireMode == AUTOWIRE_BY_NAME) {
  29. autowireByName(beanName, mbd, bw, newPvs);
  30. }
  31. // Add property values based on autowire by type if applicable.
  32. if (resolvedAutowireMode == AUTOWIRE_BY_TYPE) {
  33. autowireByType(beanName, mbd, bw, newPvs);
  34. }
  35. pvs = newPvs;
  36. }
  37. boolean hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors();
  38. boolean needsDepCheck = (mbd.getDependencyCheck() != AbstractBeanDefinition.DEPENDENCY_CHECK_NONE);
  39. PropertyDescriptor[] filteredPds = null;
  40. if (hasInstAwareBpps) {
  41. if (pvs == null) {
  42. pvs = mbd.getPropertyValues();
  43. }
  44. for (InstantiationAwareBeanPostProcessor bp : getBeanPostProcessorCache().instantiationAware) {
  45. PropertyValues pvsToUse = bp.postProcessProperties(pvs, bw.getWrappedInstance(), beanName);
  46. if (pvsToUse == null) {
  47. if (filteredPds == null) {
  48. filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
  49. }
  50. pvsToUse = bp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName);
  51. if (pvsToUse == null) {
  52. return;
  53. }
  54. }
  55. pvs = pvsToUse;
  56. }
  57. }
  58. if (needsDepCheck) {
  59. if (filteredPds == null) {
  60. filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
  61. }
  62. checkDependencies(beanName, mbd, filteredPds, pvs);
  63. }
  64. if (pvs != null) {
  65. applyPropertyValues(beanName, mbd, bw, pvs);
  66. }
  67. }
  1. protected Object initializeBean(String beanName, Object bean, @Nullable RootBeanDefinition mbd) {
  2. if (System.getSecurityManager() != null) {
  3. AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
  4. invokeAwareMethods(beanName, bean);
  5. return null;
  6. }, getAccessControlContext());
  7. }
  8. else {
  9. //唤醒Aware方法
  10. invokeAwareMethods(beanName, bean);
  11. }
  12. Object wrappedBean = bean;
  13. if (mbd == null || !mbd.isSynthetic()) {
  14. //执行BeanPostProcessor的 BeforeInitialization
  15. wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
  16. }
  17. try {
  18. //调用初始化方法
  19. invokeInitMethods(beanName, wrappedBean, mbd);
  20. }
  21. catch (Throwable ex) {
  22. throw new BeanCreationException(
  23. (mbd != null ? mbd.getResourceDescription() : null),
  24. beanName, "Invocation of init method failed", ex);
  25. }
  26. if (mbd == null || !mbd.isSynthetic()) {
  27. //执行初始化后方法
  28. wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
  29. }
  30. return wrappedBean;
  31. }

5.检测parentBeanFactory

6.将XML存储的GernericBeanDefinition转换为Root

7.寻找依赖

8.不同Scope进行bean的创建

9.类型转换

总结

image.png