我们分析Spring的bean创建从DefaultListableBeanFactory 类开始,在Spring启动时,最终会调用DefaultListableBeanFactory.preInstantiateSingletons()方法来创建Spring bean。

  1. public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory
  2. implements ConfigurableListableBeanFactory, BeanDefinitionRegistry, Serializable {
  3. // ...省略代码
  4. @Override
  5. public void preInstantiateSingletons() throws BeansException {
  6. if (logger.isTraceEnabled()) {
  7. logger.trace("Pre-instantiating singletons in " + this);
  8. }
  9. // Iterate over a copy to allow for init methods which in turn register new bean definitions.
  10. // While this may not be part of the regular factory bootstrap, it does otherwise work fine.
  11. List<String> beanNames = new ArrayList<>(this.beanDefinitionNames);
  12. // Trigger initialization of all non-lazy singleton beans...
  13. // 循环所有非惰性(就是需要启动Spring容器就需要注册到IOC容器的bean)注册到IOC容器
  14. for (String beanName : beanNames) {
  15. RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);
  16. if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {
  17. // 是FactoryBean类型的bean
  18. // FactoryBean类型的bean,在实例化bean变身后返回getObject()方法的值做为bean
  19. // 具体看FactoryBean 的介绍
  20. if (isFactoryBean(beanName)) {
  21. // FactoryBean类型的bean,bean的本身通过beanName加前缀&获取
  22. Object bean = getBean(FACTORY_BEAN_PREFIX + beanName);
  23. if (bean instanceof FactoryBean) {
  24. final FactoryBean<?> factory = (FactoryBean<?>) bean;
  25. boolean isEagerInit;
  26. if (System.getSecurityManager() != null && factory instanceof SmartFactoryBean) {
  27. isEagerInit = AccessController.doPrivileged((PrivilegedAction<Boolean>)
  28. ((SmartFactoryBean<?>) factory)::isEagerInit,
  29. getAccessControlContext());
  30. }
  31. else {
  32. isEagerInit = (factory instanceof SmartFactoryBean &&
  33. ((SmartFactoryBean<?>) factory).isEagerInit());
  34. }
  35. if (isEagerInit) {
  36. getBean(beanName);
  37. }
  38. }
  39. }
  40. else {
  41. // 获取bean
  42. getBean(beanName);
  43. }
  44. }
  45. }
  46. // 对SmartInitializingSingleton 类型的bean,在bean全部注册到IOC后进行回调
  47. for (String beanName : beanNames) {
  48. Object singletonInstance = getSingleton(beanName);
  49. if (singletonInstance instanceof SmartInitializingSingleton) {
  50. final SmartInitializingSingleton smartSingleton = (SmartInitializingSingleton) singletonInstance;
  51. if (System.getSecurityManager() != null) {
  52. AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
  53. smartSingleton.afterSingletonsInstantiated();
  54. return null;
  55. }, getAccessControlContext());
  56. }
  57. else {
  58. smartSingleton.afterSingletonsInstantiated();
  59. }
  60. }
  61. }
  62. }
  63. // ...省略代码
  64. }

preInstantiateSingletons()方法中最终会执行AbstractBeanFactory.doGetBean()方法来创建bean,接下来介绍doGetBean()方法的具体是怎么样创建出一个bean的。

  1. protected <T> T doGetBean(final String name, @Nullable final Class<T> requiredType,
  2. @Nullable final Object[] args, boolean typeCheckOnly) throws BeansException {
  3. final String beanName = transformedBeanName(name);
  4. Object bean;
  5. // 因为对于Spring的单实例bean被正式创建成功后,会保存到缓存中,确保bean为一个单实例bean
  6. // 所以先从缓存中获取Bean,如果缓存中有说明bean已经被创建了,直接返回
  7. Object sharedInstance = getSingleton(beanName);
  8. if (sharedInstance != null && args == null) {
  9. if (logger.isTraceEnabled()) {
  10. if (isSingletonCurrentlyInCreation(beanName)) {
  11. logger.trace("Returning eagerly cached instance of singleton bean '" + beanName +
  12. "' that is not fully initialized yet - a consequence of a circular reference");
  13. }
  14. else {
  15. logger.trace("Returning cached instance of singleton bean '" + beanName + "'");
  16. }
  17. }
  18. bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);
  19. }
  20. else {
  21. // Fail if we're already creating this bean instance:
  22. // We're assumably within a circular reference.
  23. // 校验bean是否在创建中,如果在创建中说明可能存在循环依赖
  24. if (isPrototypeCurrentlyInCreation(beanName)) {
  25. throw new BeanCurrentlyInCreationException(beanName);
  26. }
  27. // Check if bean definition exists in this factory.
  28. BeanFactory parentBeanFactory = getParentBeanFactory();
  29. if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
  30. // Not found -> check parent.
  31. String nameToLookup = originalBeanName(name);
  32. if (parentBeanFactory instanceof AbstractBeanFactory) {
  33. return ((AbstractBeanFactory) parentBeanFactory).doGetBean(
  34. nameToLookup, requiredType, args, typeCheckOnly);
  35. }
  36. else if (args != null) {
  37. // Delegation to parent with explicit args.
  38. return (T) parentBeanFactory.getBean(nameToLookup, args);
  39. }
  40. else if (requiredType != null) {
  41. // No args -> delegate to standard getBean method.
  42. return parentBeanFactory.getBean(nameToLookup, requiredType);
  43. }
  44. else {
  45. return (T) parentBeanFactory.getBean(nameToLookup);
  46. }
  47. }
  48. if (!typeCheckOnly) {
  49. markBeanAsCreated(beanName);
  50. }
  51. try {
  52. final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
  53. checkMergedBeanDefinition(mbd, beanName, args);
  54. // Guarantee initialization of beans that the current bean depends on.
  55. String[] dependsOn = mbd.getDependsOn();
  56. if (dependsOn != null) {
  57. for (String dep : dependsOn) {
  58. if (isDependent(beanName, dep)) {
  59. throw new BeanCreationException(mbd.getResourceDescription(), beanName,
  60. "Circular depends-on relationship between '" + beanName + "' and '" + dep + "'");
  61. }
  62. registerDependentBean(dep, beanName);
  63. try {
  64. getBean(dep);
  65. }
  66. catch (NoSuchBeanDefinitionException ex) {
  67. throw new BeanCreationException(mbd.getResourceDescription(), beanName,
  68. "'" + beanName + "' depends on missing bean '" + dep + "'", ex);
  69. }
  70. }
  71. }
  72. // Create bean instance.
  73. if (mbd.isSingleton()) {
  74. // 获取单实例bean
  75. sharedInstance = getSingleton(beanName, () -> {
  76. try {
  77. // 创建bean
  78. return createBean(beanName, mbd, args);
  79. }
  80. catch (BeansException ex) {
  81. // Explicitly remove instance from singleton cache: It might have been put there
  82. // eagerly by the creation process, to allow for circular reference resolution.
  83. // Also remove any beans that received a temporary reference to the bean.
  84. destroySingleton(beanName);
  85. throw ex;
  86. }
  87. });
  88. bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
  89. }
  90. else if (mbd.isPrototype()) {
  91. // It's a prototype -> create a new instance.
  92. Object prototypeInstance = null;
  93. try {
  94. beforePrototypeCreation(beanName);
  95. prototypeInstance = createBean(beanName, mbd, args);
  96. }
  97. finally {
  98. afterPrototypeCreation(beanName);
  99. }
  100. bean = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);
  101. }
  102. else {
  103. String scopeName = mbd.getScope();
  104. final Scope scope = this.scopes.get(scopeName);
  105. if (scope == null) {
  106. throw new IllegalStateException("No Scope registered for scope name '" + scopeName + "'");
  107. }
  108. try {
  109. Object scopedInstance = scope.get(beanName, () -> {
  110. beforePrototypeCreation(beanName);
  111. try {
  112. return createBean(beanName, mbd, args);
  113. }
  114. finally {
  115. afterPrototypeCreation(beanName);
  116. }
  117. });
  118. bean = getObjectForBeanInstance(scopedInstance, name, beanName, mbd);
  119. }
  120. catch (IllegalStateException ex) {
  121. throw new BeanCreationException(beanName,
  122. "Scope '" + scopeName + "' is not active for the current thread; consider " +
  123. "defining a scoped proxy for this bean if you intend to refer to it from a singleton",
  124. ex);
  125. }
  126. }
  127. }
  128. catch (BeansException ex) {
  129. cleanupAfterBeanCreationFailure(beanName);
  130. throw ex;
  131. }
  132. }
  133. // Check if required type matches the type of the actual bean instance.
  134. if (requiredType != null && !requiredType.isInstance(bean)) {
  135. try {
  136. T convertedBean = getTypeConverter().convertIfNecessary(bean, requiredType);
  137. if (convertedBean == null) {
  138. throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
  139. }
  140. return convertedBean;
  141. }
  142. catch (TypeMismatchException ex) {
  143. if (logger.isTraceEnabled()) {
  144. logger.trace("Failed to convert bean '" + name + "' to required type '" +
  145. ClassUtils.getQualifiedName(requiredType) + "'", ex);
  146. }
  147. throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
  148. }
  149. }
  150. return (T) bean;
  151. }

1.缓存中获取Bean

为解决A类依赖B类,B类依赖A类这种依赖注入问题,Spring通过三级缓存解决。三级缓存其实就是三个Map对象,用来存放创建的bean,key为beanName,value为bean对象。最终创建出的完整bean会存在一级缓存singletonObjects中。
一级缓存:最终创建好的完整bean
二级缓存:只实例化,没有进行初始化、赋值的bean
三级缓存:一个ObjectFactory对象,bean在只实例化,没有进行初始化、赋值和增强(创建bean的代理)的时候就将bean的实例放到ObjectFactory中,当出现循环依赖时,从三级缓存中取出ObjectFactory,并调用getObject()回调方法,执行bean的代理创建,如果bean需要被代理

直接尝试从缓存获取或者singletonFactories中的获取ObjectFactory获取,检查缓存中或者实例工厂中是否有对应实例,因为在创建单例bean的时候会存在依赖注入的情况,而在创建依赖的时候为了避免循环依赖,Spring创建bean的原则是不等bean创建完成就会创建bean的ObjectFactory对象提早曝光,也就是将ObjectFactory加入缓存中,一但下个bean创建的时候需要依赖上个bean则直接使用ObjectFactory对象注入

  1. @Nullable
  2. protected Object getSingleton(String beanName, boolean allowEarlyReference) {
  3. // 从一级缓存中查找bean
  4. Object singletonObject = this.singletonObjects.get(beanName);
  5. // 一级缓存中没有bean,并且当前bean正在创建中
  6. if (singletonObject == null && isSingletonCurrentlyInCreation(beanName)) {
  7. // 锁主一级缓存
  8. synchronized (this.singletonObjects) {
  9. // 从二级缓存中查找bean
  10. singletonObject = this.earlySingletonObjects.get(beanName);
  11. // 二级缓存中没有bean,并且这是一个不健全的bean(只实例化)
  12. if (singletonObject == null && allowEarlyReference) {
  13. // 三级缓存中查找
  14. ObjectFactory<?> singletonFactory = this.singletonFactories.get(beanName);
  15. // 三级缓存中查找到ObjectFactory
  16. if (singletonFactory != null) {
  17. // 回调getObject()方法
  18. // 就是执行SmartInstantiationAwareBeanPostProcessor 类型的getEarlyBeanReference()方法
  19. // bean的代理对象创建会在这里创建
  20. // 有一个AbstractAutoProxyCreator类实现SmartInstantiationAwareBeanPostProcessor接口
  21. // 在getEarlyBeanReference()方法中创建bean的代理
  22. singletonObject = singletonFactory.getObject();
  23. // 一旦执行了ObjectFactory的回调方法getObject(),就把bean从三级缓存中移除,放到二级缓存中
  24. // 目的很简单,就是不要重复的回调ObjectFactory的getObject()方法
  25. // 以创建bean的代理为例,重复调用会重复创建代理
  26. this.earlySingletonObjects.put(beanName, singletonObject);
  27. // 从三级缓存中移除bean
  28. // 二级缓存和三级缓存是互斥的
  29. // 这句话的意思三级缓存中存在的bean不会在二级缓存中存在
  30. // 二级缓存中存在的bean不会在三级缓存中存在
  31. this.singletonFactories.remove(beanName);
  32. }
  33. }
  34. }
  35. }
  36. return singletonObject;
  37. }

2. 循环依赖校验

前面从三级缓存中查找bean,都没有找到,校验bean是否在创建中,如果在创建中说明此事存在循环依赖,抛出异常

  1. // bean在创建中,抛出正在创建中的异常
  2. if (isPrototypeCurrentlyInCreation(beanName)) {
  3. throw new BeanCurrentlyInCreationException(beanName);
  4. }

查找bean是否在创建中

  1. protected boolean isPrototypeCurrentlyInCreation(String beanName) {
  2. // 正在创建的bean实例,如果找到说明bean正在创建中
  3. Object curVal = this.prototypesCurrentlyInCreation.get();
  4. return (curVal != null &&
  5. (curVal.equals(beanName) || (curVal instanceof Set && ((Set<?>) curVal).contains(beanName))));
  6. }

3. 检查bean的定义信息

先检查bean的定义信息有没有存在,如果没存在且有父类Beanfactory对象,那么父类工厂对象中创建bean

  1. // 当前bean的父类BeanFactory工厂对象
  2. BeanFactory parentBeanFactory = getParentBeanFactory();
  3. // 如果从没有找到bean的定义信息,从父类BeanFactory中创建bean
  4. if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
  5. // Not found -> check parent.
  6. String nameToLookup = originalBeanName(name);
  7. if (parentBeanFactory instanceof AbstractBeanFactory) {
  8. return ((AbstractBeanFactory) parentBeanFactory).doGetBean(
  9. nameToLookup, requiredType, args, typeCheckOnly);
  10. }
  11. else if (args != null) {
  12. // Delegation to parent with explicit args.
  13. return (T) parentBeanFactory.getBean(nameToLookup, args);
  14. }
  15. else if (requiredType != null) {
  16. // No args -> delegate to standard getBean method.
  17. return parentBeanFactory.getBean(nameToLookup, requiredType);
  18. }
  19. else {
  20. return (T) parentBeanFactory.getBean(nameToLookup);
  21. }
  22. }

从beanDefinitionMap 中查找bean的定义信息

  1. @Override
  2. public boolean containsBeanDefinition(String beanName) {
  3. Assert.notNull(beanName, "Bean name must not be null");
  4. return this.beanDefinitionMap.containsKey(beanName);
  5. }

4.合并bean的定义信息

5. 抽象类校验

如果是抽象类,不允许实例化抛出异常

  1. protected void checkMergedBeanDefinition(RootBeanDefinition mbd, String beanName, @Nullable Object[] args)
  2. throws BeanDefinitionStoreException {
  3. if (mbd.isAbstract()) {
  4. throw new BeanIsAbstractException(beanName);
  5. }
  6. }

6.创建优先级高的Bean

所谓优先级高的bean是指在当前bean被创建之前,需要先被创建出来的bean

  1. // 当前bean创建之前需要被创建的beanName
  2. String[] dependsOn = mbd.getDependsOn();
  3. if (dependsOn != null) {
  4. for (String dep : dependsOn) {
  5. if (isDependent(beanName, dep)) {
  6. throw new BeanCreationException(mbd.getResourceDescription(), beanName,
  7. "Circular depends-on relationship between '" + beanName + "' and '" + dep + "'");
  8. }
  9. registerDependentBean(dep, beanName);
  10. try {
  11. // 调用getBean 创建bean
  12. getBean(dep);
  13. }
  14. catch (NoSuchBeanDefinitionException ex) {
  15. throw new BeanCreationException(mbd.getResourceDescription(), beanName,
  16. "'" + beanName + "' depends on missing bean '" + dep + "'", ex);
  17. }
  18. }
  19. }

7. 获取单实例Bean

getSingleton()方法很简单,只干了四件事
第一:将bean加入到创建中的集合中,表示bean正在创建中
第二:调用创建bean方法
第三:bean成功创建后,将bean从创建中的集合中移除,表示bean不在创建中
第四:将创建完成的bean加入到singletonObjects缓存中,下一次获取该Bean时,直接从缓存中获取

  1. // 检查单实例Bean
  2. if (mbd.isSingleton()) {
  3. // 获取单实例bean
  4. sharedInstance = getSingleton(beanName, () -> {
  5. try {
  6. // 回调方法,创建bean
  7. return createBean(beanName, mbd, args);
  8. }
  9. catch (BeansException ex) {
  10. // Explicitly remove instance from singleton cache: It might have been put there
  11. // eagerly by the creation process, to allow for circular reference resolution.
  12. // Also remove any beans that received a temporary reference to the bean.
  13. destroySingleton(beanName);
  14. throw ex;
  15. }
  16. });
  17. bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
  18. }

getSingletion()方法的作用是对Bean创建之前标识bean正在创建中,和bean创建之后移除bean正在创建中的标识,之后将bean加入到singtionObjects中

  1. public Object getSingleton(String beanName, ObjectFactory<?> singletonFactory) {
  2. Assert.notNull(beanName, "Bean name must not be null");
  3. synchronized (this.singletonObjects) {
  4. // 从缓存中获取bean
  5. Object singletonObject = this.singletonObjects.get(beanName);
  6. // 缓存中没有bean
  7. if (singletonObject == null) {
  8. if (this.singletonsCurrentlyInDestruction) {
  9. throw new BeanCreationNotAllowedException(beanName,
  10. "Singleton bean creation not allowed while singletons of this factory are in destruction " +
  11. "(Do not request a bean from a BeanFactory in a destroy method implementation!)");
  12. }
  13. if (logger.isDebugEnabled()) {
  14. logger.debug("Creating shared instance of singleton bean '" + beanName + "'");
  15. }
  16. // 将bean标识为正在创建中
  17. beforeSingletonCreation(beanName);
  18. boolean newSingleton = false;
  19. boolean recordSuppressedExceptions = (this.suppressedExceptions == null);
  20. if (recordSuppressedExceptions) {
  21. this.suppressedExceptions = new LinkedHashSet<>();
  22. }
  23. try {
  24. // 回调方法,执行createBean()方法创建bean
  25. singletonObject = singletonFactory.getObject();
  26. newSingleton = true;
  27. }
  28. catch (IllegalStateException ex) {
  29. // Has the singleton object implicitly appeared in the meantime ->
  30. // if yes, proceed with it since the exception indicates that state.
  31. singletonObject = this.singletonObjects.get(beanName);
  32. if (singletonObject == null) {
  33. throw ex;
  34. }
  35. }
  36. catch (BeanCreationException ex) {
  37. if (recordSuppressedExceptions) {
  38. for (Exception suppressedException : this.suppressedExceptions) {
  39. ex.addRelatedCause(suppressedException);
  40. }
  41. }
  42. throw ex;
  43. }
  44. finally {
  45. if (recordSuppressedExceptions) {
  46. this.suppressedExceptions = null;
  47. }
  48. // bean创建完之后,移除bean正在创建中的标识
  49. afterSingletonCreation(beanName);
  50. }
  51. if (newSingleton) {
  52. // 将bean 加入到singletonObjects Map缓存中
  53. addSingleton(beanName, singletonObject);
  54. }
  55. }
  56. return singletonObject;
  57. }
  58. }

8. 正式创建Bean

  1. protected Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
  2. throws BeanCreationException {
  3. if (logger.isTraceEnabled()) {
  4. logger.trace("Creating instance of bean '" + beanName + "'");
  5. }
  6. RootBeanDefinition mbdToUse = mbd;
  7. // Make sure bean class is actually resolved at this point, and
  8. // clone the bean definition in case of a dynamically resolved Class
  9. // which cannot be stored in the shared merged bean definition.
  10. Class<?> resolvedClass = resolveBeanClass(mbd, beanName);
  11. if (resolvedClass != null && !mbd.hasBeanClass() && mbd.getBeanClassName() != null) {
  12. mbdToUse = new RootBeanDefinition(mbd);
  13. mbdToUse.setBeanClass(resolvedClass);
  14. }
  15. // Prepare method overrides.
  16. try {
  17. mbdToUse.prepareMethodOverrides();
  18. }
  19. catch (BeanDefinitionValidationException ex) {
  20. throw new BeanDefinitionStoreException(mbdToUse.getResourceDescription(),
  21. beanName, "Validation of method overrides failed", ex);
  22. }
  23. try {
  24. // 先给后置处理器一个机会,通过后置处理器创建bean
  25. Object bean = resolveBeforeInstantiation(beanName, mbdToUse);
  26. // 后置处理器创建了bean,直接返回
  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. //bean 创建bean的核心逻辑
  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. }

8.1. 实例化前后置处理器创建Bean

  1. protected Object resolveBeforeInstantiation(String beanName, RootBeanDefinition mbd) {
  2. Object bean = null;
  3. if (!Boolean.FALSE.equals(mbd.beforeInstantiationResolved)) {
  4. // Make sure bean class is actually resolved at this point.
  5. if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
  6. Class<?> targetType = determineTargetType(beanName, mbd);
  7. if (targetType != null) {
  8. // 执行后置处理器的before方法
  9. bean = applyBeanPostProcessorsBeforeInstantiation(targetType, beanName);
  10. // 执行后置处理器的after方法
  11. if (bean != null) {
  12. bean = applyBeanPostProcessorsAfterInitialization(bean, beanName);
  13. }
  14. }
  15. }
  16. mbd.beforeInstantiationResolved = (bean != null);
  17. }
  18. return bean;
  19. }

执行InstantiationAwareBeanPostProcessor 类型的后置处理器
InstantiationAwareBeanPostProcessor 典型的有创建Bean的动态代理后置处理器AbstractAdvisorAutoProxyCreator类,该类会对需要代理的类创建相应的动态代理对象

  1. @Nullable
  2. protected Object applyBeanPostProcessorsBeforeInstantiation(Class<?> beanClass, String beanName) {
  3. // 循环所有BeanPostProcessor后置处理器
  4. for (BeanPostProcessor bp : getBeanPostProcessors()) {
  5. // 只处理InstantiationAwareBeanPostProcessor类型的后置处理器
  6. if (bp instanceof InstantiationAwareBeanPostProcessor) {
  7. InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
  8. // 执行后置处理器before方法
  9. Object result = ibp.postProcessBeforeInstantiation(beanClass, beanName);
  10. if (result != null) {
  11. return result;
  12. }
  13. }
  14. }
  15. return null;
  16. }

如果bean被创建,执行后置处理器的after方法,Spring中的规则是在bean的初始化后尽可能保证将注册的后置处理器postProcessAfterInitialization()方法应用到该bean中,因为如果在实例化前置处理器中的bean不为空,那么便不会再次经历普通的bean创建过程,所以只能在这里应用后置处理器的postProcessAfterInitialization()方法

调用BeanPostProcessor类型的postProcessAfterInitialization()方法

  1. @Override
  2. public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName)
  3. throws BeansException {
  4. Object result = existingBean;
  5. for (BeanPostProcessor processor : getBeanPostProcessors()) {
  6. Object current = processor.postProcessAfterInitialization(result, beanName);
  7. if (current == null) {
  8. return result;
  9. }
  10. result = current;
  11. }
  12. return result;
  13. }

8.2. 创建bean核心

  1. protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final @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. final 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. applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
  22. }
  23. catch (Throwable ex) {
  24. throw new BeanCreationException(mbd.getResourceDescription(), beanName,
  25. "Post-processing of merged bean definition failed", ex);
  26. }
  27. mbd.postProcessed = true;
  28. }
  29. }
  30. // Eagerly cache singletons to be able to resolve circular references
  31. // even when triggered by lifecycle interfaces like BeanFactoryAware.
  32. boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences &&
  33. isSingletonCurrentlyInCreation(beanName));
  34. if (earlySingletonExposure) {
  35. if (logger.isTraceEnabled()) {
  36. logger.trace("Eagerly caching bean '" + beanName +
  37. "' to allow for resolving potential circular references");
  38. }
  39. // bean实例化后,提早将bean放到三级缓存singletonFactories中
  40. addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
  41. }
  42. // Initialize the bean instance.
  43. Object exposedObject = bean;
  44. try {
  45. // 属性赋值
  46. populateBean(beanName, mbd, instanceWrapper);
  47. // 初始化bean
  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. if (earlySingletonExposure) {
  60. Object earlySingletonReference = getSingleton(beanName, false);
  61. if (earlySingletonReference != null) {
  62. if (exposedObject == bean) {
  63. exposedObject = earlySingletonReference;
  64. }
  65. else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) {
  66. String[] dependentBeans = getDependentBeans(beanName);
  67. Set<String> actualDependentBeans = new LinkedHashSet<>(dependentBeans.length);
  68. for (String dependentBean : dependentBeans) {
  69. if (!removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) {
  70. actualDependentBeans.add(dependentBean);
  71. }
  72. }
  73. if (!actualDependentBeans.isEmpty()) {
  74. throw new BeanCurrentlyInCreationException(beanName,
  75. "Bean with name '" + beanName + "' has been injected into other beans [" +
  76. StringUtils.collectionToCommaDelimitedString(actualDependentBeans) +
  77. "] in its raw version as part of a circular reference, but has eventually been " +
  78. "wrapped. This means that said other beans do not use the final version of the " +
  79. "bean. This is often the result of over-eager type matching - consider using " +
  80. "'getBeanNamesForType' with the 'allowEagerInit' flag turned off, for example.");
  81. }
  82. }
  83. }
  84. }
  85. // Register bean as disposable.
  86. try {
  87. registerDisposableBeanIfNecessary(beanName, bean, mbd);
  88. }
  89. catch (BeanDefinitionValidationException ex) {
  90. throw new BeanCreationException(
  91. mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex);
  92. }
  93. return exposedObject;
  94. }

8.2.1. 实例化bean

  1. protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) {
  2. // 解析bean 的class
  3. Class<?> beanClass = resolveBeanClass(mbd, beanName);
  4. if (beanClass != null && !Modifier.isPublic(beanClass.getModifiers()) && !mbd.isNonPublicAccessAllowed()) {
  5. throw new BeanCreationException(mbd.getResourceDescription(), beanName,
  6. "Bean class isn't public, and non-public access not allowed: " + beanClass.getName());
  7. }
  8. Supplier<?> instanceSupplier = mbd.getInstanceSupplier();
  9. if (instanceSupplier != null) {
  10. return obtainFromSupplier(instanceSupplier, beanName);
  11. }
  12. // 使用工厂方法实例化bean
  13. if (mbd.getFactoryMethodName() != null) {
  14. return instantiateUsingFactoryMethod(beanName, mbd, args);
  15. }
  16. // Shortcut when re-creating the same bean...
  17. boolean resolved = false;
  18. boolean autowireNecessary = false;
  19. if (args == null) {
  20. synchronized (mbd.constructorArgumentLock) {
  21. if (mbd.resolvedConstructorOrFactoryMethod != null) {
  22. resolved = true;
  23. autowireNecessary = mbd.constructorArgumentsResolved;
  24. }
  25. }
  26. }
  27. if (resolved) {
  28. if (autowireNecessary) {
  29. // 使用非默认构造函数实例化bean
  30. return autowireConstructor(beanName, mbd, null, null);
  31. }
  32. else {
  33. // 使用默认构造函数实例化bean
  34. return instantiateBean(beanName, mbd);
  35. }
  36. }
  37. // 根据参数解析,决定使用哪个构造函数实例化bean
  38. Constructor<?>[] ctors = determineConstructorsFromBeanPostProcessors(beanClass, beanName);
  39. if (ctors != null || mbd.getResolvedAutowireMode() == AUTOWIRE_CONSTRUCTOR ||
  40. mbd.hasConstructorArgumentValues() || !ObjectUtils.isEmpty(args)) {
  41. return autowireConstructor(beanName, mbd, ctors, args);
  42. }
  43. // Preferred constructors for default construction?
  44. ctors = mbd.getPreferredConstructors();
  45. if (ctors != null) {
  46. return autowireConstructor(beanName, mbd, ctors, null);
  47. }
  48. // No special handling: simply use no-arg constructor.
  49. return instantiateBean(beanName, mbd);
  50. }

8.2.2. 提早曝光Bean

为了解决循环依赖问题,提早将bean曝光(这个bean还是一个没有任何属性填充的bean,就是一个只实例化但还没有对bean中的属性赋值),添加到addSingletonFactory中,后面如果有执行getBean()循环依赖该bean时,会先从singletonFactory中获取bean直接返回,从而中断后面的populateBean()方法,就不会再次执行getBean(),这样就解决了循环依赖

  1. boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences &&
  2. isSingletonCurrentlyInCreation(beanName));
  3. if (earlySingletonExposure) {
  4. if (logger.isTraceEnabled()) {
  5. logger.trace("Eagerly caching bean '" + beanName +
  6. "' to allow for resolving potential circular references");
  7. }
  8. // bean实例化后,将ObjectFactory对象放到缓存中,这个ObjectFactory提供一个回调方法getObject()
  9. // 此时如果有循环依赖,创建另一个bean时会回调getObject()方法
  10. addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
  11. }

ObjectFactory回调方法getObject(),只执行SmartInstantiationAwareBeanPostProcessor类型,典型的有AbstractAutoProxyCreator类创建bean的代理对象

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

8.2.3. 属性填充

对bean的熟悉进行填充,将各个属性值注入,其中可能存在依赖于其他bean的属性,则会递归初始依赖bean,即调用getBean()方法

  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. // 执行bean实例化后的后置处理器
  13. // 执行InstantiationAwareBeanPostProcessor类型中的postProcessAfterInstantiation()方法
  14. // 如果postProcessAfterInstantiation()方法返回false就终止后续的执行,既属性注入执行,可以用来控制程序是否继续进行属性填充
  15. if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
  16. for (BeanPostProcessor bp : getBeanPostProcessors()) {
  17. if (bp instanceof InstantiationAwareBeanPostProcessor) {
  18. InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
  19. if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {
  20. return;
  21. }
  22. }
  23. }
  24. }
  25. PropertyValues pvs = (mbd.hasPropertyValues() ? mbd.getPropertyValues() : null);
  26. int resolvedAutowireMode = mbd.getResolvedAutowireMode();
  27. if (resolvedAutowireMode == AUTOWIRE_BY_NAME || resolvedAutowireMode == AUTOWIRE_BY_TYPE) {
  28. MutablePropertyValues newPvs = new MutablePropertyValues(pvs);
  29. // Add property values based on autowire by name if applicable.
  30. if (resolvedAutowireMode == AUTOWIRE_BY_NAME) {
  31. autowireByName(beanName, mbd, bw, newPvs);
  32. }
  33. // Add property values based on autowire by type if applicable.
  34. if (resolvedAutowireMode == AUTOWIRE_BY_TYPE) {
  35. autowireByType(beanName, mbd, bw, newPvs);
  36. }
  37. pvs = newPvs;
  38. }
  39. boolean hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors();
  40. boolean needsDepCheck = (mbd.getDependencyCheck() != AbstractBeanDefinition.DEPENDENCY_CHECK_NONE);
  41. PropertyDescriptor[] filteredPds = null;
  42. if (hasInstAwareBpps) {
  43. if (pvs == null) {
  44. pvs = mbd.getPropertyValues();
  45. }
  46. for (BeanPostProcessor bp : getBeanPostProcessors()) {
  47. if (bp instanceof InstantiationAwareBeanPostProcessor) {
  48. InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
  49. PropertyValues pvsToUse = ibp.postProcessProperties(pvs, bw.getWrappedInstance(), beanName);
  50. if (pvsToUse == null) {
  51. if (filteredPds == null) {
  52. filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
  53. }
  54. pvsToUse = ibp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName);
  55. if (pvsToUse == null) {
  56. return;
  57. }
  58. }
  59. pvs = pvsToUse;
  60. }
  61. }
  62. }
  63. if (needsDepCheck) {
  64. if (filteredPds == null) {
  65. filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
  66. }
  67. checkDependencies(beanName, mbd, filteredPds, pvs);
  68. }
  69. if (pvs != null) {
  70. applyPropertyValues(beanName, mbd, bw, pvs);
  71. }
  72. }

8.2.3.1. 实例化后的后置处理器

执行InstantiationAwareBeanPostProcessor类型中的postProcessAfterInstantiation()方法,如果postProcessAfterInstantiation()方法返回false就终止后续的执行,既属性注入执行,可以用来控制程序是否继续进行属性填充

  1. if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
  2. for (BeanPostProcessor bp : getBeanPostProcessors()) {
  3. if (bp instanceof InstantiationAwareBeanPostProcessor) {
  4. InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
  5. if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {
  6. return;
  7. }
  8. }
  9. }
  10. }

8.2.3.2. 按名称注入属性

  1. protected void autowireByName(
  2. String beanName, AbstractBeanDefinition mbd, BeanWrapper bw, MutablePropertyValues pvs) {
  3. // 获取bean 被注入的属性
  4. String[] propertyNames = unsatisfiedNonSimpleProperties(mbd, bw);
  5. for (String propertyName : propertyNames) {
  6. // beanName 存在BeanDefinition信息
  7. if (containsBean(propertyName)) {
  8. // 调用getBean创建bean
  9. Object bean = getBean(propertyName);
  10. pvs.add(propertyName, bean);
  11. registerDependentBean(propertyName, beanName);
  12. if (logger.isTraceEnabled()) {
  13. logger.trace("Added autowiring by name from bean name '" + beanName +
  14. "' via property '" + propertyName + "' to bean named '" + propertyName + "'");
  15. }
  16. }
  17. else {
  18. if (logger.isTraceEnabled()) {
  19. logger.trace("Not autowiring property '" + propertyName + "' of bean '" + beanName +
  20. "' by name: no matching bean found");
  21. }
  22. }
  23. }
  24. }

8.2.3.3. 按类型输入属性

  1. protected void autowireByType(
  2. String beanName, AbstractBeanDefinition mbd, BeanWrapper bw, MutablePropertyValues pvs) {
  3. TypeConverter converter = getCustomTypeConverter();
  4. if (converter == null) {
  5. converter = bw;
  6. }
  7. Set<String> autowiredBeanNames = new LinkedHashSet<>(4);
  8. // 获取所有属性名称
  9. String[] propertyNames = unsatisfiedNonSimpleProperties(mbd, bw);
  10. for (String propertyName : propertyNames) {
  11. try {
  12. PropertyDescriptor pd = bw.getPropertyDescriptor(propertyName);
  13. // Don't try autowiring by type for type Object: never makes sense,
  14. // even if it technically is a unsatisfied, non-simple property.
  15. if (Object.class != pd.getPropertyType()) {
  16. MethodParameter methodParam = BeanUtils.getWriteMethodParameter(pd);
  17. // Do not allow eager init for type matching in case of a prioritized post-processor.
  18. boolean eager = !(bw.getWrappedInstance() instanceof PriorityOrdered);
  19. DependencyDescriptor desc = new AutowireByTypeDependencyDescriptor(methodParam, eager);
  20. Object autowiredArgument = resolveDependency(desc, beanName, autowiredBeanNames, converter);
  21. if (autowiredArgument != null) {
  22. pvs.add(propertyName, autowiredArgument);
  23. }
  24. for (String autowiredBeanName : autowiredBeanNames) {
  25. registerDependentBean(autowiredBeanName, beanName);
  26. if (logger.isTraceEnabled()) {
  27. logger.trace("Autowiring by type from bean name '" + beanName + "' via property '" +
  28. propertyName + "' to bean named '" + autowiredBeanName + "'");
  29. }
  30. }
  31. autowiredBeanNames.clear();
  32. }
  33. }
  34. catch (BeansException ex) {
  35. throw new UnsatisfiedDependencyException(mbd.getResourceDescription(), beanName, propertyName, ex);
  36. }
  37. }
  38. }

8.2.3.4. 执行postProcessPropertyValues()

对属性真正应用到bean上前执行InstantiationAwareBeanPostProcessor的postProcessPropertyValues()方法。
典型应用是可以扩展RequiredAnnotationBeanPostProcessor类中对属性验证

  1. if (hasInstAwareBpps) {
  2. if (pvs == null) {
  3. pvs = mbd.getPropertyValues();
  4. }
  5. for (BeanPostProcessor bp : getBeanPostProcessors()) {
  6. if (bp instanceof InstantiationAwareBeanPostProcessor) {
  7. // 执行InstantiationAwareBeanPostProcessor 类型中的postProcessPropertyValues()方法
  8. InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
  9. PropertyValues pvsToUse = ibp.postProcessProperties(pvs, bw.getWrappedInstance(), beanName);
  10. if (pvsToUse == null) {
  11. if (filteredPds == null) {
  12. filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
  13. }
  14. pvsToUse = ibp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName);
  15. if (pvsToUse == null) {
  16. return;
  17. }
  18. }
  19. pvs = pvsToUse;
  20. }
  21. }
  22. }

8.2.3.5. 将属性应用到Bean中

将属性从PropertyValues应用到bean中

  1. protected void applyPropertyValues(String beanName, BeanDefinition mbd, BeanWrapper bw, PropertyValues pvs) {
  2. if (pvs.isEmpty()) {
  3. return;
  4. }
  5. if (System.getSecurityManager() != null && bw instanceof BeanWrapperImpl) {
  6. ((BeanWrapperImpl) bw).setSecurityContext(getAccessControlContext());
  7. }
  8. MutablePropertyValues mpvs = null;
  9. List<PropertyValue> original;
  10. if (pvs instanceof MutablePropertyValues) {
  11. mpvs = (MutablePropertyValues) pvs;
  12. if (mpvs.isConverted()) {
  13. // Shortcut: use the pre-converted values as-is.
  14. try {
  15. bw.setPropertyValues(mpvs);
  16. return;
  17. }
  18. catch (BeansException ex) {
  19. throw new BeanCreationException(
  20. mbd.getResourceDescription(), beanName, "Error setting property values", ex);
  21. }
  22. }
  23. original = mpvs.getPropertyValueList();
  24. }
  25. else {
  26. original = Arrays.asList(pvs.getPropertyValues());
  27. }
  28. TypeConverter converter = getCustomTypeConverter();
  29. if (converter == null) {
  30. converter = bw;
  31. }
  32. BeanDefinitionValueResolver valueResolver = new BeanDefinitionValueResolver(this, beanName, mbd, converter);
  33. // Create a deep copy, resolving any references for values.
  34. List<PropertyValue> deepCopy = new ArrayList<>(original.size());
  35. boolean resolveNecessary = false;
  36. for (PropertyValue pv : original) {
  37. if (pv.isConverted()) {
  38. deepCopy.add(pv);
  39. }
  40. else {
  41. String propertyName = pv.getName();
  42. Object originalValue = pv.getValue();
  43. if (originalValue == AutowiredPropertyMarker.INSTANCE) {
  44. Method writeMethod = bw.getPropertyDescriptor(propertyName).getWriteMethod();
  45. if (writeMethod == null) {
  46. throw new IllegalArgumentException("Autowire marker for property without write method: " + pv);
  47. }
  48. originalValue = new DependencyDescriptor(new MethodParameter(writeMethod, 0), true);
  49. }
  50. Object resolvedValue = valueResolver.resolveValueIfNecessary(pv, originalValue);
  51. Object convertedValue = resolvedValue;
  52. boolean convertible = bw.isWritableProperty(propertyName) &&
  53. !PropertyAccessorUtils.isNestedOrIndexedProperty(propertyName);
  54. if (convertible) {
  55. convertedValue = convertForProperty(resolvedValue, propertyName, bw, converter);
  56. }
  57. // Possibly store converted value in merged bean definition,
  58. // in order to avoid re-conversion for every created bean instance.
  59. if (resolvedValue == originalValue) {
  60. if (convertible) {
  61. pv.setConvertedValue(convertedValue);
  62. }
  63. deepCopy.add(pv);
  64. }
  65. else if (convertible && originalValue instanceof TypedStringValue &&
  66. !((TypedStringValue) originalValue).isDynamic() &&
  67. !(convertedValue instanceof Collection || ObjectUtils.isArray(convertedValue))) {
  68. pv.setConvertedValue(convertedValue);
  69. deepCopy.add(pv);
  70. }
  71. else {
  72. resolveNecessary = true;
  73. deepCopy.add(new PropertyValue(pv, convertedValue));
  74. }
  75. }
  76. }
  77. if (mpvs != null && !resolveNecessary) {
  78. mpvs.setConverted();
  79. }
  80. // Set our (possibly massaged) deep copy.
  81. try {
  82. bw.setPropertyValues(new MutablePropertyValues(deepCopy));
  83. }
  84. catch (BeansException ex) {
  85. throw new BeanCreationException(
  86. mbd.getResourceDescription(), beanName, "Error setting property values", ex);
  87. }
  88. }

8.2.4. 初始化Bean

初始化bean这里是当bean的属性赋值完成后,执行bean的初始化方法,在执行初始化方法之前,会先执行各种Aware接口的子类方法。

  1. protected Object initializeBean(final String beanName, final Object bean, @Nullable RootBeanDefinition mbd) {
  2. if (System.getSecurityManager() != null) {
  3. AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
  4. // 执行Aware 接口的子类方法
  5. invokeAwareMethods(beanName, bean);
  6. return null;
  7. }, getAccessControlContext());
  8. }
  9. else {
  10. // 执行Aware 接口的子类方法
  11. invokeAwareMethods(beanName, bean);
  12. }
  13. Object wrappedBean = bean;
  14. if (mbd == null || !mbd.isSynthetic()) {
  15. // 初始化方法前,执行初始化后置处理器before()方法
  16. wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
  17. }
  18. try {
  19. // 执行初始化方法
  20. invokeInitMethods(beanName, wrappedBean, mbd);
  21. }
  22. catch (Throwable ex) {
  23. throw new BeanCreationException(
  24. (mbd != null ? mbd.getResourceDescription() : null),
  25. beanName, "Invocation of init method failed", ex);
  26. }
  27. if (mbd == null || !mbd.isSynthetic()) {
  28. // 初始化方法后,执行初始化后置处理器after()方法
  29. wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
  30. }
  31. return wrappedBean;
  32. }

8.2.4.1. 执行Aware

先执行BeanNameAwar、BeanClassLoaderAware、BeanFactoryAware 三类Aware子类的对应方法,可以通过实现这些类型的Aware接口,在执行bean的初始化方法之前做些扩展

  1. private void invokeAwareMethods(final String beanName, final Object bean) {
  2. if (bean instanceof Aware) {
  3. if (bean instanceof BeanNameAware) {
  4. ((BeanNameAware) bean).setBeanName(beanName);
  5. }
  6. if (bean instanceof BeanClassLoaderAware) {
  7. ClassLoader bcl = getBeanClassLoader();
  8. if (bcl != null) {
  9. ((BeanClassLoaderAware) bean).setBeanClassLoader(bcl);
  10. }
  11. }
  12. if (bean instanceof BeanFactoryAware) {
  13. ((BeanFactoryAware) bean).setBeanFactory(AbstractAutowireCapableBeanFactory.this);
  14. }
  15. }
  16. }

8.2.4.2. 初始化之前后置处理器

在执行bean的初始化方法之前,先执行初始化后置处理器before()方法,典型的应用是ApplicationContextAwareProcessor后置处理器,用于在执行bean的初始化方法之前,执行EnvironmentAware、EmbeddedValueResolverAware、ResourceLoaderAware、ApplicationEventPublisherAware、MessageSourceAware、ApplicationContextAware 这些Aware

  1. if (mbd == null || !mbd.isSynthetic()) {
  2. wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
  3. }

执行BeanPostProcessor后置处理器的before方法

  1. public Object applyBeanPostProcessorsBeforeInitialization(Object existingBean, String beanName)
  2. throws BeansException {
  3. Object result = existingBean;
  4. // 执行所有BeanPostProcess后置处理器的postProcessBeforeInitialization()方法
  5. for (BeanPostProcessor processor : getBeanPostProcessors()) {
  6. Object current = processor.postProcessBeforeInitialization(result, beanName);
  7. if (current == null) {
  8. return result;
  9. }
  10. result = current;
  11. }
  12. return result;
  13. }

8.2.4.3. 执行初始化方法

bean的初始化方法分两类,一类是实现InitializingBean接口的bean,执行afterPropertiesSet()方法,一类是自定义的初始化方法,通过反射执行。

  1. protected void invokeInitMethods(String beanName, final Object bean, @Nullable RootBeanDefinition mbd)
  2. throws Throwable {
  3. // 执行InitializingBean类型的bean的初始化方法afterPropertiesSet()
  4. boolean isInitializingBean = (bean instanceof InitializingBean);
  5. if (isInitializingBean && (mbd == null || !mbd.isExternallyManagedInitMethod("afterPropertiesSet"))) {
  6. if (logger.isTraceEnabled()) {
  7. logger.trace("Invoking afterPropertiesSet() on bean with name '" + beanName + "'");
  8. }
  9. if (System.getSecurityManager() != null) {
  10. try {
  11. AccessController.doPrivileged((PrivilegedExceptionAction<Object>) () -> {
  12. ((InitializingBean) bean).afterPropertiesSet();
  13. return null;
  14. }, getAccessControlContext());
  15. }
  16. catch (PrivilegedActionException pae) {
  17. throw pae.getException();
  18. }
  19. }
  20. else {
  21. ((InitializingBean) bean).afterPropertiesSet();
  22. }
  23. }
  24. // 执行自定义初始化方法,反射执行
  25. if (mbd != null && bean.getClass() != NullBean.class) {
  26. String initMethodName = mbd.getInitMethodName();
  27. if (StringUtils.hasLength(initMethodName) &&
  28. !(isInitializingBean && "afterPropertiesSet".equals(initMethodName)) &&
  29. !mbd.isExternallyManagedInitMethod(initMethodName)) {
  30. invokeCustomInitMethod(beanName, bean, mbd);
  31. }
  32. }
  33. }

8.2.4.4. 初始化方法之后后置处理器

执行初始化方法之后,调用BeanPostProcessor的postProcessAfterInitialization()方法来扩展业务需求

  1. if (mbd == null || !mbd.isSynthetic()) {
  2. wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
  3. }

执行BeanPostProcessor后置处理器的after方法

  1. @Override
  2. public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName)
  3. throws BeansException {
  4. Object result = existingBean;
  5. // 执行所有BeanPostProcessor后置处理器的postProcessAfterInitialization()方法
  6. for (BeanPostProcessor processor : getBeanPostProcessors()) {
  7. Object current = processor.postProcessAfterInitialization(result, beanName);
  8. if (current == null) {
  9. return result;
  10. }
  11. result = current;
  12. }
  13. return result;
  14. }

9. BeanFactory类型的bean

对于是BeanFactory类型的bean,我们在创建bean之后,不是直接返回bean的信息,而是返回getObject()方法的返回值。这样做的目的是为bean提供扩展,如:MyBatis 和Spring的整合,MyBatis的接口其实是不能实例化的,我们将接口转换为一个Bean,最后调用BeanFactory方法的getObject()方法返回接口的代理对象

  1. protected Object getObjectForBeanInstance(
  2. Object beanInstance, String name, String beanName, @Nullable RootBeanDefinition mbd) {
  3. // 对于FactoryBean类型的,获取他的原型是在beanName前加&
  4. // 校验是获取FactoryBean类型的原型bean
  5. if (BeanFactoryUtils.isFactoryDereference(name)) {
  6. if (beanInstance instanceof NullBean) {
  7. return beanInstance;
  8. }
  9. if (!(beanInstance instanceof FactoryBean)) {
  10. throw new BeanIsNotAFactoryException(beanName, beanInstance.getClass());
  11. }
  12. if (mbd != null) {
  13. mbd.isFactoryBean = true;
  14. }
  15. return beanInstance;
  16. }
  17. // 不是FactoryBean的bean直接返回
  18. if (!(beanInstance instanceof FactoryBean)) {
  19. return beanInstance;
  20. }
  21. Object object = null;
  22. if (mbd != null) {
  23. mbd.isFactoryBean = true;
  24. }
  25. else {
  26. // 从缓存中获取bean
  27. object = getCachedObjectForFactoryBean(beanName);
  28. }
  29. // 缓存中为空调用getObject()方法
  30. if (object == null) {
  31. // Return bean instance from factory.
  32. FactoryBean<?> factory = (FactoryBean<?>) beanInstance;
  33. // Caches object obtained from FactoryBean if it is a singleton.
  34. if (mbd == null && containsBeanDefinition(beanName)) {
  35. mbd = getMergedLocalBeanDefinition(beanName);
  36. }
  37. boolean synthetic = (mbd != null && mbd.isSynthetic());
  38. // 调用getObject()方法获取bean
  39. object = getObjectFromFactoryBean(factory, beanName, !synthetic);
  40. }
  41. return object;
  42. }