导图

24.spring源码之IOC - 图1

整体流程图

image.png

故事的小黄花.从AnnotationConfigApplicationContext的第十六步开始:
接下来调用

  1. // Instantiate all remaining (non-lazy-init) singletons.
  2. beanFactory.preInstantiateSingletons();

看看整体图
image.png
然后进入DefaultListableBeanFactory(BeanFactory),看看我们自定义的初始化函数在什么时候执行
image.png

  1. public class DefaultListableBeanFactory{
  2. /**
  3. * Ensure that all non-lazy-init singletons are instantiated, also considering
  4. * {@link org.springframework.beans.factory.FactoryBean FactoryBeans}.
  5. * Typically invoked at the end of factory setup, if desired.
  6. * Note: This may have left the factory with some beans already initialized!
  7. * Call {@link #destroySingletons()} for full cleanup in this case.
  8. * @see #destroySingletons()
  9. */
  10. public void preInstantiateSingletons() throws BeansException {
  11. // Trigger initialization of all non-lazy singleton beans...
  12. if (isFactoryBean(beanName)) {
  13. Object bean = getBean(FACTORY_BEAN_PREFIX + beanName);
  14. if (bean instanceof FactoryBean) {
  15. }else{
  16. getBean(beanName);
  17. }
  18. // Trigger post-initialization callback for all applicable beans...
  19. }
  20. //Implementation of BeanFactory interface 原始
  21. @Override
  22. public Object getBean(String name) throws BeansException {
  23. return doGetBean(name, null, null, false);
  24. }
  25. /**
  26. * Return an instance, which may be shared or independent, of the specified bean.
  27. * @return an instance of the bean
  28. * @throws BeansException if the bean could not be created
  29. */
  30. protected <T> T doGetBean(
  31. /**
  32. * 1.Eagerly check singleton cache for manually registered singletons. 是否缓存中有了(手动注册)
  33. * 2.缓存没有
  34. * 2.1// We're assumably within a circular reference.处理循环引用
  35. 2.2 Check if bean definition exists in this factory.检查定义在工厂
  36. 2.3Guarantee initialization of beans that the current bean depends on.确保依赖都已经有了
  37. 2.4真正创建逻辑getSingleton
  38. */
  39. // Create bean instance.
  40. if (mbd.isSingleton()) {
  41. sharedInstance = getSingleton(beanName, () -> {
  42. try {
  43. return createBean(beanName, mbd, args);
  44. }
  45. catch (BeansException ex) {
  46. // Explicitly remove instance from singleton cache: It might have been put there
  47. // eagerly by the creation process, to allow for circular reference resolution.
  48. // Also remove any beans that received a temporary reference to the bean.
  49. destroySingleton(beanName);
  50. throw ex;
  51. }
  52. });
  53. bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
  54. }
  55. }
  56. /**
  57. * Return the (raw) singleton object registered under the given name,
  58. * creating and registering a new one if none registered yet.
  59. * @param singletonFactory the ObjectFactory to lazily create the singleton with, if necessary 这里的singletonFactory就是上面的那个lambda方法
  60. * @return the registered singleton object
  61. */
  62. public Object getSingleton(String beanName, ObjectFactory<?> singletonFactory) {
  63. singletonObject = singletonFactory.getObject();//lambda调用createBean
  64. }
  65. /**
  66. * Implementation of relevant AbstractBeanFactory template methods!
  67. * Central method of this class:
  68. * 1.creates a bean instance,
  69. * 2.populates the bean instance
  70. * 3.applies post-processors, etc.
  71. * @see #doCreateBean
  72. */
  73. @Override
  74. protected Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) throws BeanCreationException {
  75. Object beanInstance = doCreateBean(beanName, mbdToUse, args);
  76. }
  77. /**
  78. * Actually create the specified bean. Pre-creation processing has already happened at this point, e.g. checking {@code postProcessBeforeInstantiation} callbacks.
  79. * <p>Differentiates between default bean instantiation, use of a factory method, and autowiring a constructor.
  80. * @param mbd the merged bean definition for the bean
  81. */
  82. protected Object doCreateBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
  83. throws BeanCreationException {
  84. // Instantiate the bean.
  85. // Initialize the bean instance.
  86. Object exposedObject = bean;
  87. try {
  88. populateBean(beanName, mbd, instanceWrapper);
  89. exposedObject = initializeBean(beanName, exposedObject, mbd);
  90. }
  91. // Register bean as disposable.
  92. }
  93. /**
  94. 后置处理器前处理
  95. 执行初始化方法
  96. 后置处理器后处理
  97. */
  98. protected Object initializeBean(String beanName, Object bean, @Nullable RootBeanDefinition mbd) {
  99. invokeAwareMethods(beanName, bean);
  100. if (mbd == null || !mbd.isSynthetic()) {
  101. wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
  102. }
  103. invokeInitMethods(beanName, wrappedBean, mbd);
  104. if (mbd == null || !mbd.isSynthetic()) {
  105. wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
  106. }
  107. return wrappedBean;
  108. }
  109. /**
  110. * Give a bean a chance to react now all its properties are set,
  111. * and a chance to know about its owning bean factory (this object).
  112. * This means checking whether the bean implements InitializingBean or defines
  113. * a custom init method, and invoking the necessary callback(s) if it does.
  114. * @param beanName the bean name in the factory (for debugging purposes)
  115. * @param bean the new bean instance we may need to initialize
  116. * @param mbd the merged bean definition that the bean was created with
  117. * (can also be {@code null}, if given an existing bean instance)
  118. * @throws Throwable if thrown by init methods or by the invocation process
  119. * @see #invokeCustomInitMethod
  120. */
  121. protected void invokeInitMethods(String beanName, Object bean, @Nullable RootBeanDefinition mbd) throws Throwable {
  122. //先执行 InitializingBean实现类逻辑afterPropertiesSet方法调用
  123. ((InitializingBean) bean).afterPropertiesSet();
  124. //在执行 手动指定@Bean(initMethod="init", destroyMethod="destroy")逻辑
  125. invokeCustomInitMethod(beanName, bean, mbd);//反射调用
  126. }
  127. //后置处理器的[前处理]相关逻辑
  128. @Override
  129. public Object applyBeanPostProcessorsBeforeInitialization(Object existingBean, String beanName)
  130. throws BeansException {
  131. Object result = existingBean;
  132. for (BeanPostProcessor processor : getBeanPostProcessors()) {
  133. Object current = processor.postProcessBeforeInitialization(result, beanName);
  134. if (current == null) {
  135. return result;
  136. }
  137. result = current;
  138. }
  139. return result;
  140. }
  141. //后置处理器的[后处理]相关逻辑
  142. @Override
  143. public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName)
  144. throws BeansException {
  145. Object result = existingBean;
  146. for (BeanPostProcessor processor : getBeanPostProcessors()) {
  147. Object current = processor.postProcessAfterInitialization(result, beanName);
  148. if (current == null) {
  149. return result;
  150. }
  151. result = current;
  152. }
  153. return result;
  154. }
  155. }

看看spring默认的beanPostProcessors
这些后置处理器在DefaultListableBeanFactory中 作为一个属性,肯定就有一个顺序的问题
image.png
如果我们用了JSR-250的注解
image.png
那么CommonAnnotationBeanPostProcessor这个就会帮我们在某个时机(周期)执行对应的方法,底层也是反射调用方法

24.spring源码之IOC - 图7
第三个

解析

24.spring源码之IOC - 图8

全流程图

分析部分代码

  1. public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport implements ConfigurableBeanFactory {
  2. protected <T> T doGetBean(
  3. String name, @Nullable Class<T> requiredType, @Nullable Object[] args, boolean typeCheckOnly)
  4. throws BeansException {
  5. // ①处理别名BeanName、②处理带&符的工厂BeanName
  6. String beanName = transformedBeanName(name);
  7. Object bean;
  8. // Eagerly check singleton cache for manually registered singletons.
  9. // 先尝试从缓存中获取Bean实例,这个位置就是三级缓存解决循环依赖的方法
  10. Object sharedInstance = getSingleton(beanName);
  11. if (sharedInstance != null && args == null) {
  12. if (logger.isTraceEnabled()) {
  13. if (isSingletonCurrentlyInCreation(beanName)) {
  14. logger.trace("Returning eagerly cached instance of singleton bean '" + beanName +
  15. "' that is not fully initialized yet - a consequence of a circular reference");
  16. }
  17. else {
  18. logger.trace("Returning cached instance of singleton bean '" + beanName + "'");
  19. }
  20. }
  21. // 1. 如果 sharedInstance 是普通的 Bean 实例,则下面的方法会直接返回
  22. // 2. 如果 sharedInstance 是工厂Bean类型,则需要获取 getObject 方法,可以参考关于 FactoryBean 的实现类 工厂的会走这里
  23. bean = 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. if (isPrototypeCurrentlyInCreation(beanName)) {
  29. throw new BeanCurrentlyInCreationException(beanName);
  30. }
  31. // Check if bean definition exists in this factory.
  32. BeanFactory parentBeanFactory = getParentBeanFactory();
  33. //父工厂存在并且当前 bean 不存在于当前bean工厂 则到父工厂查找 bean 实例
  34. if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
  35. // Not found -> check parent.
  36. String nameToLookup = originalBeanName(name);
  37. if (parentBeanFactory instanceof AbstractBeanFactory) {
  38. return ((AbstractBeanFactory) parentBeanFactory).doGetBean(
  39. nameToLookup, requiredType, args, typeCheckOnly);
  40. }
  41. else if (args != null) {
  42. // Delegation to parent with explicit args.
  43. return (T) parentBeanFactory.getBean(nameToLookup, args);
  44. }
  45. else if (requiredType != null) {
  46. // No args -> delegate to standard getBean method.
  47. return parentBeanFactory.getBean(nameToLookup, requiredType);
  48. }
  49. else {
  50. return (T) parentBeanFactory.getBean(nameToLookup);
  51. }
  52. }
  53. if (!typeCheckOnly) {
  54. markBeanAsCreated(beanName);
  55. }
  56. try {
  57. // 从容器 getMergedLocalBeanDefinition 获取 beanName 对应的 GenericBeanDefinition,转换为 RootBeanDefinition
  58. RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
  59. checkMergedBeanDefinition(mbd, beanName, args);
  60. // Guarantee initialization of beans that the current bean depends on.
  61. // 处理使用了 depends-on 注解的依赖创建 bean 实例
  62. String[] dependsOn = mbd.getDependsOn();
  63. if (dependsOn != null) {
  64. for (String dep : dependsOn) {
  65. // 监测是否存在 depends-on 循环依赖,若存在则会抛出异常 注解的话会处理@DependsOn("adidas") xml的话会处理<bean id="userService" class="com.lcd.demo.service.UserService" depends-on="userDao"/>
  66. if (isDependent(beanName, dep)) {
  67. throw new BeanCreationException(mbd.getResourceDescription(), beanName,
  68. "Circular depends-on relationship between '" + beanName + "' and '" + dep + "'");
  69. }
  70. // 注册依赖记录
  71. registerDependentBean(dep, beanName);
  72. try {
  73. // 加载 depends-on 依赖(dep 是 depends-on 缩写)
  74. getBean(dep);
  75. }
  76. catch (NoSuchBeanDefinitionException ex) {
  77. throw new BeanCreationException(mbd.getResourceDescription(), beanName,
  78. "'" + beanName + "' depends on missing bean '" + dep + "'", ex);
  79. }
  80. }
  81. }
  82. // 创建单例 bean 实例
  83. // Create bean instance.
  84. if (mbd.isSingleton()) {
  85. //真正逻辑
  86. sharedInstance = getSingleton(beanName, () -> {
  87. try {
  88. //创建Bean
  89. return createBean(beanName, mbd, args);
  90. }
  91. catch (BeansException ex) {
  92. // Explicitly remove instance from singleton cache: It might have been put there
  93. // eagerly by the creation process, to allow for circular reference resolution.
  94. // Also remove any beans that received a temporary reference to the bean.
  95. destroySingleton(beanName);
  96. throw ex;
  97. }
  98. });
  99. bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
  100. }
  101. // 创建多例 bean 实例
  102. else if (mbd.isPrototype()) {
  103. // It's a prototype -> create a new instance.
  104. Object prototypeInstance = null;
  105. try {
  106. beforePrototypeCreation(beanName);
  107. prototypeInstance = createBean(beanName, mbd, args);
  108. }
  109. finally {
  110. afterPrototypeCreation(beanName);
  111. }
  112. bean = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);
  113. }
  114. else {
  115. String scopeName = mbd.getScope();
  116. if (!StringUtils.hasLength(scopeName)) {
  117. throw new IllegalStateException("No scope name defined for bean ´" + beanName + "'");
  118. }
  119. Scope scope = this.scopes.get(scopeName);
  120. if (scope == null) {
  121. throw new IllegalStateException("No Scope registered for scope name '" + scopeName + "'");
  122. }
  123. try {
  124. Object scopedInstance = scope.get(beanName, () -> {
  125. beforePrototypeCreation(beanName);
  126. try {
  127. return createBean(beanName, mbd, args);
  128. }
  129. finally {
  130. afterPrototypeCreation(beanName);
  131. }
  132. });
  133. bean = getObjectForBeanInstance(scopedInstance, name, beanName, mbd);
  134. }
  135. catch (IllegalStateException ex) {
  136. throw new BeanCreationException(beanName,
  137. "Scope '" + scopeName + "' is not active for the current thread; consider " +
  138. "defining a scoped proxy for this bean if you intend to refer to it from a singleton",
  139. ex);
  140. }
  141. }
  142. }
  143. catch (BeansException ex) {
  144. cleanupAfterBeanCreationFailure(beanName);
  145. throw ex;
  146. }
  147. }
  148. // 如果需要类型转换,这里会进行操作
  149. // Check if required type matches the type of the actual bean instance.
  150. if (requiredType != null && !requiredType.isInstance(bean)) {
  151. try {
  152. T convertedBean = getTypeConverter().convertIfNecessary(bean, requiredType);
  153. if (convertedBean == null) {
  154. throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
  155. }
  156. return convertedBean;
  157. }
  158. catch (TypeMismatchException ex) {
  159. if (logger.isTraceEnabled()) {
  160. logger.trace("Failed to convert bean '" + name + "' to required type '" +
  161. ClassUtils.getQualifiedName(requiredType) + "'", ex);
  162. }
  163. throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
  164. }
  165. }
  166. return (T) bean;
  167. }
  168. }