个人随笔
目录
一个简单的例子来探寻Spring实例化bean执行源码的主脉络(三):扫包和实例化
2021-07-19 23:11:33

在上一篇文章中,我们跟踪源码终于知道了什么时候解析配置类,在this()方法中,我们大概实现了如下操作。

1、初始化了AnnotationConfigApplicationContext对象
2、初始化了AnnotationConfigApplicationContext的父对象GenericApplicationContext
3、GenericApplicationContext对象里面初始化了一个beanFactory成员变量,对象为DefaultListableBeanFactory
4、初始化了一个reader:AnnotatedBeanDefinitionReader
5、初始化reder的过程中把几个后置处理器比如internalPersistenceAnnotationProcessor和internalAutowiredAnnotationProcessor等放到了DefaultListableBeanFactory中的beanDefinitionMap中,key为bean的名称,值为beanDefinition放的应该是这些后置处理器的相关类定义
6、初始化了一个scanner:ClassPathBeanDefinitionScanner

然后在register(componentClasses);方法把配置类注册到DefaultListableBeanFactory的beanDefinitionMap中。接着在refresh();中的invokeBeanFactoryPostProcessors(beanFactory);解析配置类,把@ComponentScan(basePackages = “com.suibibk.spring”)路径下的所有加了@Component注解的类注册到DefaultListableBeanFactory的beanDefinitionMap中。

一个简单的例子来探寻Spring实例化bean执行源码的主脉络(一):this()方法
一个简单的例子来探寻Spring实例化bean执行源码的主脉络(二):解析配置类

接下来就应该是bean初始化了,毕竟该有的东西都已经在DefaultListableBeanFactory的beanDefinitionMap中了。

我们这里先接着上面两篇的源码路径,首先是开始直接创建AnnotationConfigApplicationContext对象

  1. ApplicationContext context = new AnnotationConfigApplicationContext(SpringConfiguration.class);
  1. /**
  2. * Create a new AnnotationConfigApplicationContext, deriving bean definitions
  3. * from the given component classes and automatically refreshing the context.
  4. * @param componentClasses one or more component classes — for example,
  5. * {@link Configuration @Configuration} classes
  6. */
  7. public AnnotationConfigApplicationContext(Class<?>... componentClasses) {
  8. this();
  9. register(componentClasses);
  10. refresh();
  11. }
  1. @Override
  2. public void refresh() throws BeansException, IllegalStateException {
  3. synchronized (this.startupShutdownMonitor) {
  4. // Prepare this context for refreshing.
  5. prepareRefresh();
  6. // Tell the subclass to refresh the internal bean factory.
  7. ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
  8. // Prepare the bean factory for use in this context.
  9. prepareBeanFactory(beanFactory);
  10. try {
  11. // Allows post-processing of the bean factory in context subclasses.
  12. postProcessBeanFactory(beanFactory);
  13. // Invoke factory processors registered as beans in the context.
  14. invokeBeanFactoryPostProcessors(beanFactory);
  15. // Register bean processors that intercept bean creation.
  16. registerBeanPostProcessors(beanFactory);
  17. // Initialize message source for this context.
  18. initMessageSource();
  19. // Initialize event multicaster for this context.
  20. initApplicationEventMulticaster();
  21. // Initialize other special beans in specific context subclasses.
  22. onRefresh();
  23. // Check for listener beans and register them.
  24. registerListeners();
  25. // Instantiate all remaining (non-lazy-init) singletons.
  26. finishBeanFactoryInitialization(beanFactory);
  27. // Last step: publish corresponding event.
  28. finishRefresh();
  29. }
  30. catch (BeansException ex) {
  31. if (logger.isWarnEnabled()) {
  32. logger.warn("Exception encountered during context initialization - " +
  33. "cancelling refresh attempt: " + ex);
  34. }
  35. // Destroy already created singletons to avoid dangling resources.
  36. destroyBeans();
  37. // Reset 'active' flag.
  38. cancelRefresh(ex);
  39. // Propagate exception to caller.
  40. throw ex;
  41. }
  42. finally {
  43. // Reset common introspection caches in Spring's core, since we
  44. // might not ever need metadata for singleton beans anymore...
  45. resetCommonCaches();
  46. }
  47. }
  48. }

啥时候开始对bean进行实例化的

在上一篇文章中,我们分析到了

  1. // Invoke factory processors registered as beans in the context.
  2. invokeBeanFactoryPostProcessors(beanFactory);

得出了在这个方法中把@ComponentScan(basePackages = “com.suibibk.spring”)路径下的所有加了@Component注解的类注册到DefaultListableBeanFactory的beanDefinitionMap中这篇文章的目标就是找到啥时候开始对bean进行实例化的,毕竟我们后面就直接用

  1. User user = (User) context.getBean("user");

获取bean对象了,毕竟我们都知道,spring在容器初始化完成后,所有的Singleton对象就全部都初始化完了,所以肯定是在后面几行代码做了这些操作

  1. // Register bean processors that intercept bean creation.
  2. registerBeanPostProcessors(beanFactory);
  3. // Initialize message source for this context.
  4. initMessageSource();
  5. // Initialize event multicaster for this context.
  6. initApplicationEventMulticaster();
  7. // Initialize other special beans in specific context subclasses.
  8. onRefresh();
  9. // Check for listener beans and register them.
  10. registerListeners();
  11. // Instantiate all remaining (non-lazy-init) singletons.
  12. finishBeanFactoryInitialization(beanFactory);
  13. // Last step: publish corresponding event.
  14. finishRefresh();

先看第一行代码

  1. // Register bean processors that intercept bean creation.
  2. registerBeanPostProcessors(beanFactory);

注册拦截bean创建的bean处理器?感觉跟初始化bean没啥关系,点进去看看

  1. public static void registerBeanPostProcessors(
  2. ConfigurableListableBeanFactory beanFactory, AbstractApplicationContext applicationContext) {
  3. //获取bean后置处理器的名称,这里就是在this()那里初始化的那些bean postprocessor //比如:比如internalPersistenceAnnotationProcessor和internalAutowiredAnnotationProcessor
  4. //还有自己写的:public class MyBeanPostProcessors implements BeanPostProcessor
  5. String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanPostProcessor.class, true, false);
  6. // Register BeanPostProcessorChecker that logs an info message when
  7. // a bean is created during BeanPostProcessor instantiation, i.e. when
  8. // a bean is not eligible for getting processed by all BeanPostProcessors.
  9. int beanProcessorTargetCount = beanFactory.getBeanPostProcessorCount() + 1 + postProcessorNames.length;
  10. beanFactory.addBeanPostProcessor(new BeanPostProcessorChecker(beanFactory, beanProcessorTargetCount));
  11. // Separate between BeanPostProcessors that implement PriorityOrdered,
  12. // Ordered, and the rest.
  13. List<BeanPostProcessor> priorityOrderedPostProcessors = new ArrayList<>();
  14. List<BeanPostProcessor> internalPostProcessors = new ArrayList<>();
  15. List<String> orderedPostProcessorNames = new ArrayList<>();
  16. List<String> nonOrderedPostProcessorNames = new ArrayList<>();
  17. //循环遍历postProcessor
  18. for (String ppName : postProcessorNames) {
  19. if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
  20. //获得bean
  21. BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
  22. priorityOrderedPostProcessors.add(pp);
  23. if (pp instanceof MergedBeanDefinitionPostProcessor) {
  24. internalPostProcessors.add(pp);
  25. }
  26. }
  27. else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
  28. orderedPostProcessorNames.add(ppName);
  29. }
  30. else {
  31. nonOrderedPostProcessorNames.add(ppName);
  32. }
  33. }
  34. // First, register the BeanPostProcessors that implement PriorityOrdered.
  35. sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
  36. //加到BeanFactory中给后面用
  37. registerBeanPostProcessors(beanFactory, priorityOrderedPostProcessors);
  38. // Next, register the BeanPostProcessors that implement Ordered.
  39. List<BeanPostProcessor> orderedPostProcessors = new ArrayList<>(orderedPostProcessorNames.size());
  40. for (String ppName : orderedPostProcessorNames) {
  41. BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
  42. orderedPostProcessors.add(pp);
  43. if (pp instanceof MergedBeanDefinitionPostProcessor) {
  44. internalPostProcessors.add(pp);
  45. }
  46. }
  47. sortPostProcessors(orderedPostProcessors, beanFactory);
  48. registerBeanPostProcessors(beanFactory, orderedPostProcessors);
  49. // Now, register all regular BeanPostProcessors.
  50. List<BeanPostProcessor> nonOrderedPostProcessors = new ArrayList<>(nonOrderedPostProcessorNames.size());
  51. for (String ppName : nonOrderedPostProcessorNames) {
  52. BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
  53. nonOrderedPostProcessors.add(pp);
  54. if (pp instanceof MergedBeanDefinitionPostProcessor) {
  55. internalPostProcessors.add(pp);
  56. }
  57. }
  58. registerBeanPostProcessors(beanFactory, nonOrderedPostProcessors);
  59. // Finally, re-register all internal BeanPostProcessors.
  60. sortPostProcessors(internalPostProcessors, beanFactory);
  61. registerBeanPostProcessors(beanFactory, internalPostProcessors);
  62. // Re-register post-processor for detecting inner beans as ApplicationListeners,
  63. // moving it to the end of the processor chain (for picking up proxies etc).
  64. beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(applicationContext));
  65. }

大概总结下上面的步骤
1、获取所有的postProcessor
2、实例化所有的postProsessor
3、把实例化的这些bean都加到beanFactory中,其实是加到DefaultListableBeanFactory的父类AbstractAutowireCapableBeanFactory的父类AbstractBeanFactory的beanPostProcessors集合中。
4、把ApplicationListenerDetector也注册进去了,它也是一个BeanPostProcessor。

这里其实我们知道在这行代码

  1. BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);

已经进行了bean的实例化,不过我们知道,这里全是BeanPostProcessor,不是我们想要的,我们要的是扫包下面的加了@Component注解的类,所以不从这里看。只不过大概知道,后面肯定是通过getBean来获取实例化bean的。

现在我拼命来看第二行代码

  1. // Initialize message source for this context.
  2. initMessageSource();

初始化此上下文的消息源,额感觉这里也跟bean实例化没有任何关系呢!这里直接跳过先,继续看下一行

  1. // Initialize event multicaster for this context.
  2. initApplicationEventMulticaster();

初始化该上下文的事件多播器,感觉也跟bean实例化没有太大关系的,我们继续看下一行。

  1. // Initialize other special beans in specific context subclasses.
  2. onRefresh();

初始化特定上下文子类中的其他特殊bean,啥叫其它特殊的,那应该不是我们定义的bean了,点进去发现,根本就没有实现,只是一个模板方法而已,跳过,下一行

  1. // Check for listener beans and register them.
  2. registerListeners();

检查侦听器bean并注册它们,额监听器bean,看来应该也不是这里,跳过,下一行

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

实例化所有剩余的(非懒加载的)单例,看到这个注释,就觉得八九不离十是这里的,我们定义的都是单例的,并且没有加上任何@lazy注解
什么的普普通通的bean,并且看最后一行代码也不像实例化bean的代码,应该只是做一些收尾的工作

  1. // Last step: publish corresponding event.
  2. finishRefresh();

所以,所有代码应该都在finishBeanFactoryInitialization(beanFactory);里,让我们点进去看看spring怎么搞的吧

finishBeanFactoryInitialization(beanFactory)

  1. /**
  2. * Finish the initialization of this context's bean factory,
  3. * initializing all remaining singleton beans.
  4. */
  5. protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {
  6. // Initialize conversion service for this context.
  7. if (beanFactory.containsBean(CONVERSION_SERVICE_BEAN_NAME) &&
  8. beanFactory.isTypeMatch(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class)) {
  9. beanFactory.setConversionService(
  10. beanFactory.getBean(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class));
  11. }
  12. // Register a default embedded value resolver if no bean post-processor
  13. // (such as a PropertyPlaceholderConfigurer bean) registered any before:
  14. // at this point, primarily for resolution in annotation attribute values.
  15. if (!beanFactory.hasEmbeddedValueResolver()) {
  16. beanFactory.addEmbeddedValueResolver(strVal -> getEnvironment().resolvePlaceholders(strVal));
  17. }
  18. // Initialize LoadTimeWeaverAware beans early to allow for registering their transformers early.
  19. String[] weaverAwareNames = beanFactory.getBeanNamesForType(LoadTimeWeaverAware.class, false, false);
  20. for (String weaverAwareName : weaverAwareNames) {
  21. getBean(weaverAwareName);
  22. }
  23. // Stop using the temporary ClassLoader for type matching.
  24. beanFactory.setTempClassLoader(null);
  25. // Allow for caching all bean definition metadata, not expecting further changes.
  26. beanFactory.freezeConfiguration();
  27. // Instantiate all remaining (non-lazy-init) singletons.
  28. beanFactory.preInstantiateSingletons();
  29. }

大概扫一下,就可以看到最后一行就是我们的目标,毕竟跟主方法里面的注释是一摸一样的,所以可以大胆猜测是这里。

  1. // Instantiate all remaining (non-lazy-init) singletons.
  2. beanFactory.preInstantiateSingletons();
  1. @Override
  2. public void preInstantiateSingletons() throws BeansException {
  3. if (logger.isTraceEnabled()) {
  4. logger.trace("Pre-instantiating singletons in " + this);
  5. }
  6. // Iterate over a copy to allow for init methods which in turn register new bean definitions.
  7. // While this may not be part of the regular factory bootstrap, it does otherwise work fine.
  8. //获取所有需要实例化的类
  9. List<String> beanNames = new ArrayList<>(this.beanDefinitionNames);
  10. // Trigger initialization of all non-lazy singleton beans...
  11. for (String beanName : beanNames) {
  12. RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);
  13. if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {
  14. //我们的实例化的bean不是FactoryBean所以这里应该是不会执行
  15. if (isFactoryBean(beanName)) {
  16. Object bean = getBean(FACTORY_BEAN_PREFIX + beanName);
  17. if (bean instanceof FactoryBean) {
  18. FactoryBean<?> factory = (FactoryBean<?>) bean;
  19. boolean isEagerInit;
  20. if (System.getSecurityManager() != null && factory instanceof SmartFactoryBean) {
  21. isEagerInit = AccessController.doPrivileged(
  22. (PrivilegedAction<Boolean>) ((SmartFactoryBean<?>) factory)::isEagerInit,
  23. getAccessControlContext());
  24. }
  25. else {
  26. isEagerInit = (factory instanceof SmartFactoryBean &&
  27. ((SmartFactoryBean<?>) factory).isEagerInit());
  28. }
  29. if (isEagerInit) {
  30. getBean(beanName);
  31. }
  32. }
  33. }
  34. else {
  35. //执行这个逻辑
  36. getBean(beanName);
  37. }
  38. }
  39. }
  40. // Trigger post-initialization callback for all applicable beans...
  41. for (String beanName : beanNames) {
  42. Object singletonInstance = getSingleton(beanName);
  43. if (singletonInstance instanceof SmartInitializingSingleton) {
  44. SmartInitializingSingleton smartSingleton = (SmartInitializingSingleton) singletonInstance;
  45. if (System.getSecurityManager() != null) {
  46. AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
  47. smartSingleton.afterSingletonsInstantiated();
  48. return null;
  49. }, getAccessControlContext());
  50. }
  51. else {
  52. smartSingleton.afterSingletonsInstantiated();
  53. }
  54. }
  55. }
  56. }

我们要实例化的类是这样的

  1. package com.suibibk.spring;
  2. @Component
  3. public class User {
  4. private String username;
  5. private String password;
  6. public String getInfo() {
  7. return username+";"+password;
  8. }
  9. }

所以不可能是FactoryBean,所以会执行

  1. //执行这个逻辑
  2. getBean(beanName);

的逻辑

  1. @Override
  2. public Object getBean(String name) throws BeansException {
  3. return doGetBean(name, null, null, false);
  4. }

继续

  1. /**
  2. * Return an instance, which may be shared or independent, of the specified bean.
  3. * @param name the name of the bean to retrieve
  4. * @param requiredType the required type of the bean to retrieve
  5. * @param args arguments to use when creating a bean instance using explicit arguments
  6. * (only applied when creating a new instance as opposed to retrieving an existing one)
  7. * @param typeCheckOnly whether the instance is obtained for a type check,
  8. * not for actual use
  9. * @return an instance of the bean
  10. * @throws BeansException if the bean could not be created
  11. */
  12. @SuppressWarnings("unchecked")
  13. protected <T> T doGetBean(
  14. String name, @Nullable Class<T> requiredType, @Nullable Object[] args, boolean typeCheckOnly)
  15. throws BeansException {
  16. //获取bean的名称
  17. String beanName = transformedBeanName(name);
  18. Object bean;
  19. //检查手动注册的单例的缓存,一开始我们肯定是没有缓存的,所以应该不会执行这段逻辑
  20. // Eagerly check singleton cache for manually registered singletons.
  21. Object sharedInstance = getSingleton(beanName);
  22. if (sharedInstance != null && args == null) {
  23. if (logger.isTraceEnabled()) {
  24. if (isSingletonCurrentlyInCreation(beanName)) {
  25. logger.trace("Returning eagerly cached instance of singleton bean '" + beanName +
  26. "' that is not fully initialized yet - a consequence of a circular reference");
  27. }
  28. else {
  29. logger.trace("Returning cached instance of singleton bean '" + beanName + "'");
  30. }
  31. }
  32. bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);
  33. }
  34. else {
  35. // Fail if we're already creating this bean instance:
  36. // We're assumably within a circular reference.
  37. if (isPrototypeCurrentlyInCreation(beanName)) {
  38. throw new BeanCurrentlyInCreationException(beanName);
  39. }
  40. //检查这个bean定义是否已经存在工厂中了,我们的user一开始也不会执行
  41. // Check if bean definition exists in this factory.
  42. BeanFactory parentBeanFactory = getParentBeanFactory();
  43. if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
  44. // Not found -> check parent.
  45. String nameToLookup = originalBeanName(name);
  46. if (parentBeanFactory instanceof AbstractBeanFactory) {
  47. return ((AbstractBeanFactory) parentBeanFactory).doGetBean(
  48. nameToLookup, requiredType, args, typeCheckOnly);
  49. }
  50. else if (args != null) {
  51. // Delegation to parent with explicit args.
  52. return (T) parentBeanFactory.getBean(nameToLookup, args);
  53. }
  54. else if (requiredType != null) {
  55. // No args -> delegate to standard getBean method.
  56. return parentBeanFactory.getBean(nameToLookup, requiredType);
  57. }
  58. else {
  59. return (T) parentBeanFactory.getBean(nameToLookup);
  60. }
  61. }
  62. if (!typeCheckOnly) {
  63. markBeanAsCreated(beanName);
  64. }
  65. try {
  66. RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
  67. checkMergedBeanDefinition(mbd, beanName, args);
  68. // Guarantee initialization of beans that the current bean depends on.
  69. String[] dependsOn = mbd.getDependsOn();
  70. if (dependsOn != null) {
  71. for (String dep : dependsOn) {
  72. if (isDependent(beanName, dep)) {
  73. throw new BeanCreationException(mbd.getResourceDescription(), beanName,
  74. "Circular depends-on relationship between '" + beanName + "' and '" + dep + "'");
  75. }
  76. registerDependentBean(dep, beanName);
  77. try {
  78. getBean(dep);
  79. }
  80. catch (NoSuchBeanDefinitionException ex) {
  81. throw new BeanCreationException(mbd.getResourceDescription(), beanName,
  82. "'" + beanName + "' depends on missing bean '" + dep + "'", ex);
  83. }
  84. }
  85. }
  86. // Create bean instance.
  87. //创建bean的实例
  88. if (mbd.isSingleton()) {
  89. sharedInstance = getSingleton(beanName, () -> {
  90. try {
  91. return createBean(beanName, mbd, args);
  92. }
  93. catch (BeansException ex) {
  94. // Explicitly remove instance from singleton cache: It might have been put there
  95. // eagerly by the creation process, to allow for circular reference resolution.
  96. // Also remove any beans that received a temporary reference to the bean.
  97. destroySingleton(beanName);
  98. throw ex;
  99. }
  100. });
  101. bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
  102. }
  103. else if (mbd.isPrototype()) {
  104. // It's a prototype -> create a new instance.
  105. Object prototypeInstance = null;
  106. try {
  107. beforePrototypeCreation(beanName);
  108. prototypeInstance = createBean(beanName, mbd, args);
  109. }
  110. finally {
  111. afterPrototypeCreation(beanName);
  112. }
  113. bean = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);
  114. }
  115. else {
  116. String scopeName = mbd.getScope();
  117. if (!StringUtils.hasLength(scopeName)) {
  118. throw new IllegalStateException("No scope name defined for bean ´" + beanName + "'");
  119. }
  120. Scope scope = this.scopes.get(scopeName);
  121. if (scope == null) {
  122. throw new IllegalStateException("No Scope registered for scope name '" + scopeName + "'");
  123. }
  124. try {
  125. Object scopedInstance = scope.get(beanName, () -> {
  126. beforePrototypeCreation(beanName);
  127. try {
  128. return createBean(beanName, mbd, args);
  129. }
  130. finally {
  131. afterPrototypeCreation(beanName);
  132. }
  133. });
  134. bean = getObjectForBeanInstance(scopedInstance, name, beanName, mbd);
  135. }
  136. catch (IllegalStateException ex) {
  137. throw new BeanCreationException(beanName,
  138. "Scope '" + scopeName + "' is not active for the current thread; consider " +
  139. "defining a scoped proxy for this bean if you intend to refer to it from a singleton",
  140. ex);
  141. }
  142. }
  143. }
  144. catch (BeansException ex) {
  145. cleanupAfterBeanCreationFailure(beanName);
  146. throw ex;
  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. }

额这一个方法超级长,我们千万不要去搞懂每一行,要结合和注释经验猜测关键代码。注释的意思是:返回指定bean的一个实例,该实例可以是共享的,也可以是独立的。所以这个方法的目标i就是返回一个bean,实例化后的bean,这个bean就是我们的user。我们会很容易注意到下面这段代码

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

我们的bean恰好是单例的,所以肯定值执行代码createBean(beanName, mbd, args);我们根据去

  1. /**
  2. * Central method of this class: creates a bean instance,
  3. * populates the bean instance, applies post-processors, etc.
  4. * @see #doCreateBean
  5. */
  6. @Override
  7. protected Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
  8. throws BeanCreationException {
  9. if (logger.isTraceEnabled()) {
  10. logger.trace("Creating instance of bean '" + beanName + "'");
  11. }
  12. RootBeanDefinition mbdToUse = mbd;
  13. // Make sure bean class is actually resolved at this point, and
  14. // clone the bean definition in case of a dynamically resolved Class
  15. // which cannot be stored in the shared merged bean definition.
  16. //返回类的Class对象
  17. Class<?> resolvedClass = resolveBeanClass(mbd, beanName);
  18. if (resolvedClass != null && !mbd.hasBeanClass() && mbd.getBeanClassName() != null) {
  19. mbdToUse = new RootBeanDefinition(mbd);
  20. mbdToUse.setBeanClass(resolvedClass);
  21. }
  22. // Prepare method overrides.
  23. try {
  24. mbdToUse.prepareMethodOverrides();
  25. }
  26. catch (BeanDefinitionValidationException ex) {
  27. throw new BeanDefinitionStoreException(mbdToUse.getResourceDescription(),
  28. beanName, "Validation of method overrides failed", ex);
  29. }
  30. try {
  31. // Give BeanPostProcessors a chance to return a proxy instead of the target bean instance.
  32. Object bean = resolveBeforeInstantiation(beanName, mbdToUse);
  33. if (bean != null) {
  34. return bean;
  35. }
  36. }
  37. catch (Throwable ex) {
  38. throw new BeanCreationException(mbdToUse.getResourceDescription(), beanName,
  39. "BeanPostProcessor before instantiation of bean failed", ex);
  40. }
  41. try {
  42. //实例化bean
  43. Object beanInstance = doCreateBean(beanName, mbdToUse, args);
  44. if (logger.isTraceEnabled()) {
  45. logger.trace("Finished creating instance of bean '" + beanName + "'");
  46. }
  47. return beanInstance;
  48. }
  49. catch (BeanCreationException | ImplicitlyAppearedSingletonException ex) {
  50. // A previously detected exception with proper bean creation context already,
  51. // or illegal singleton state to be communicated up to DefaultSingletonBeanRegistry.
  52. throw ex;
  53. }
  54. catch (Throwable ex) {
  55. throw new BeanCreationException(
  56. mbdToUse.getResourceDescription(), beanName, "Unexpected exception during bean creation", ex);
  57. }
  58. }

注释含义为:该类的中心方法:创建一个bean实例,填充bean实例,应用后处理器等。很明显了,一切一切都会在这里找到答案。

createBean(beanName, mbd, args);

我们直接看代码

  1. //实例化bean
  2. Object beanInstance = doCreateBean(beanName, mbdToUse, args);

spring习惯性在真正开始处理的时候就用do开头的方法。mbdToUse在上面代码

  1. Class<?> resolvedClass = resolveBeanClass(mbd, beanName);
  2. if (resolvedClass != null && !mbd.hasBeanClass() && mbd.getBeanClassName() != null) {
  3. mbdToUse = new RootBeanDefinition(mbd);
  4. mbdToUse.setBeanClass(resolvedClass);
  5. }

放入了类的Class对象,beanName为要实例化的bean的名称,比如这里应该是”user”。我们继续跟踪代码

  1. /**
  2. * Actually create the specified bean. Pre-creation processing has already happened
  3. * at this point, e.g. checking {@code postProcessBeforeInstantiation} callbacks.
  4. * <p>Differentiates between default bean instantiation, use of a
  5. * factory method, and autowiring a constructor.
  6. * @param beanName the name of the bean
  7. * @param mbd the merged bean definition for the bean
  8. * @param args explicit arguments to use for constructor or factory method invocation
  9. * @return a new instance of the bean
  10. * @throws BeanCreationException if the bean could not be created
  11. * @see #instantiateBean
  12. * @see #instantiateUsingFactoryMethod
  13. * @see #autowireConstructor
  14. */
  15. protected Object doCreateBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
  16. throws BeanCreationException {
  17. // Instantiate the bean.
  18. BeanWrapper instanceWrapper = null;
  19. if (mbd.isSingleton()) {
  20. instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
  21. }
  22. //创建bean的包装对象
  23. if (instanceWrapper == null) {
  24. instanceWrapper = createBeanInstance(beanName, mbd, args);
  25. }
  26. Object bean = instanceWrapper.getWrappedInstance();
  27. Class<?> beanType = instanceWrapper.getWrappedClass();
  28. if (beanType != NullBean.class) {
  29. mbd.resolvedTargetType = beanType;
  30. }
  31. // Allow post-processors to modify the merged bean definition.
  32. synchronized (mbd.postProcessingLock) {
  33. if (!mbd.postProcessed) {
  34. try {
  35. applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
  36. }
  37. catch (Throwable ex) {
  38. throw new BeanCreationException(mbd.getResourceDescription(), beanName,
  39. "Post-processing of merged bean definition failed", ex);
  40. }
  41. mbd.postProcessed = true;
  42. }
  43. }
  44. // Eagerly cache singletons to be able to resolve circular references
  45. // even when triggered by lifecycle interfaces like BeanFactoryAware.
  46. boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences &&
  47. isSingletonCurrentlyInCreation(beanName));
  48. if (earlySingletonExposure) {
  49. if (logger.isTraceEnabled()) {
  50. logger.trace("Eagerly caching bean '" + beanName +
  51. "' to allow for resolving potential circular references");
  52. }
  53. addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
  54. }
  55. // Initialize the bean instance.
  56. Object exposedObject = bean;
  57. try {
  58. populateBean(beanName, mbd, instanceWrapper);
  59. exposedObject = initializeBean(beanName, exposedObject, mbd);
  60. }
  61. catch (Throwable ex) {
  62. if (ex instanceof BeanCreationException && beanName.equals(((BeanCreationException) ex).getBeanName())) {
  63. throw (BeanCreationException) ex;
  64. }
  65. else {
  66. throw new BeanCreationException(
  67. mbd.getResourceDescription(), beanName, "Initialization of bean failed", ex);
  68. }
  69. }
  70. if (earlySingletonExposure) {
  71. Object earlySingletonReference = getSingleton(beanName, false);
  72. if (earlySingletonReference != null) {
  73. if (exposedObject == bean) {
  74. exposedObject = earlySingletonReference;
  75. }
  76. else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) {
  77. String[] dependentBeans = getDependentBeans(beanName);
  78. Set<String> actualDependentBeans = new LinkedHashSet<>(dependentBeans.length);
  79. for (String dependentBean : dependentBeans) {
  80. if (!removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) {
  81. actualDependentBeans.add(dependentBean);
  82. }
  83. }
  84. if (!actualDependentBeans.isEmpty()) {
  85. throw new BeanCurrentlyInCreationException(beanName,
  86. "Bean with name '" + beanName + "' has been injected into other beans [" +
  87. StringUtils.collectionToCommaDelimitedString(actualDependentBeans) +
  88. "] in its raw version as part of a circular reference, but has eventually been " +
  89. "wrapped. This means that said other beans do not use the final version of the " +
  90. "bean. This is often the result of over-eager type matching - consider using " +
  91. "'getBeanNamesForType' with the 'allowEagerInit' flag turned off, for example.");
  92. }
  93. }
  94. }
  95. }
  96. // Register bean as disposable.
  97. try {
  98. registerDisposableBeanIfNecessary(beanName, bean, mbd);
  99. }
  100. catch (BeanDefinitionValidationException ex) {
  101. throw new BeanCreationException(
  102. mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex);
  103. }
  104. return exposedObject;
  105. }

好长!先看注释,大概意思是说这个方法是真正创建bean的方法,并且执行一些postProcess方法的回调,也就是会回调我们前面提到的那一批BeanPostProccessor,我们来分析下。

  1. //创建bean的包装对象
  2. if (instanceWrapper == null) {
  3. instanceWrapper = createBeanInstance(beanName, mbd, args);
  4. }

这里是先创建了bean的包装对象,看看是怎么创建的

  1. /**
  2. * Create a new instance for the specified bean, using an appropriate instantiation strategy:
  3. * factory method, constructor autowiring, or simple instantiation.
  4. * @param beanName the name of the bean
  5. * @param mbd the bean definition for the bean
  6. * @param args explicit arguments to use for constructor or factory method invocation
  7. * @return a BeanWrapper for the new instance
  8. * @see #obtainFromSupplier
  9. * @see #instantiateUsingFactoryMethod
  10. * @see #autowireConstructor
  11. * @see #instantiateBean
  12. */
  13. protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) {
  14. // Make sure bean class is actually resolved at this point.
  15. //获取Class对象
  16. Class<?> beanClass = resolveBeanClass(mbd, beanName);
  17. if (beanClass != null && !Modifier.isPublic(beanClass.getModifiers()) && !mbd.isNonPublicAccessAllowed()) {
  18. throw new BeanCreationException(mbd.getResourceDescription(), beanName,
  19. "Bean class isn't public, and non-public access not allowed: " + beanClass.getName());
  20. }
  21. Supplier<?> instanceSupplier = mbd.getInstanceSupplier();
  22. if (instanceSupplier != null) {
  23. return obtainFromSupplier(instanceSupplier, beanName);
  24. }
  25. if (mbd.getFactoryMethodName() != null) {
  26. return instantiateUsingFactoryMethod(beanName, mbd, args);
  27. }
  28. // Shortcut when re-creating the same bean...
  29. boolean resolved = false;
  30. boolean autowireNecessary = false;
  31. if (args == null) {
  32. synchronized (mbd.constructorArgumentLock) {
  33. if (mbd.resolvedConstructorOrFactoryMethod != null) {
  34. resolved = true;
  35. autowireNecessary = mbd.constructorArgumentsResolved;
  36. }
  37. }
  38. }
  39. if (resolved) {
  40. if (autowireNecessary) {
  41. return autowireConstructor(beanName, mbd, null, null);
  42. }
  43. else {
  44. return instantiateBean(beanName, mbd);
  45. }
  46. }
  47. //候选构造方法来自动装配?显然不是
  48. // Candidate constructors for autowiring?
  49. Constructor<?>[] ctors = determineConstructorsFromBeanPostProcessors(beanClass, beanName);
  50. if (ctors != null || mbd.getResolvedAutowireMode() == AUTOWIRE_CONSTRUCTOR ||
  51. mbd.hasConstructorArgumentValues() || !ObjectUtils.isEmpty(args)) {
  52. return autowireConstructor(beanName, mbd, ctors, args);
  53. }
  54. // Preferred constructors for default construction?
  55. //默认构造的优先构造参数?显然也不是
  56. ctors = mbd.getPreferredConstructors();
  57. if (ctors != null) {
  58. return autowireConstructor(beanName, mbd, ctors, null);
  59. }
  60. // No special handling: simply use no-arg constructor.
  61. //无特殊处理:只需使用无参数构造函数。 那肯定是这里了
  62. return instantiateBean(beanName, mbd);
  63. }

Create a new instance for the specified bean, using an appropriate instantiation strategy:factory method, constructor autowiring, or simple instantiation.
使用适当的实例化策略为指定bean创建一个新实例:工厂方法、构造函数自动装配或简单实例化。

我们没有用工厂方法,也没有用构造方法的模式,而是用简单的模式,所以直接执行最后一行

  1. return instantiateBean(beanName, mbd);
  1. /**
  2. * Instantiate the given bean using its default constructor.
  3. * @param beanName the name of the bean
  4. * @param mbd the bean definition for the bean
  5. * @return a BeanWrapper for the new instance
  6. */
  7. protected BeanWrapper instantiateBean(String beanName, RootBeanDefinition mbd) {
  8. try {
  9. Object beanInstance;
  10. if (System.getSecurityManager() != null) {
  11. beanInstance = AccessController.doPrivileged(
  12. (PrivilegedAction<Object>) () -> getInstantiationStrategy().instantiate(mbd, beanName, this),
  13. getAccessControlContext());
  14. }
  15. else {
  16. beanInstance = getInstantiationStrategy().instantiate(mbd, beanName, this);
  17. }
  18. BeanWrapper bw = new BeanWrapperImpl(beanInstance);
  19. initBeanWrapper(bw);
  20. return bw;
  21. }
  22. catch (Throwable ex) {
  23. throw new BeanCreationException(
  24. mbd.getResourceDescription(), beanName, "Instantiation of bean failed", ex);
  25. }
  26. }

用默认的构造器实例化一个类,我们先执行方法实例化一个对象

  1. beanInstance = getInstantiationStrategy().instantiate(mbd, beanName, this);
  1. /** Strategy for creating bean instances. */
  2. private InstantiationStrategy instantiationStrategy = new CglibSubclassingInstantiationStrategy();

这里用的策略是cglib,那这里应该是用动态代理的模式了,我们点进去看看

  1. @Override
  2. public Object instantiate(RootBeanDefinition bd, @Nullable String beanName, BeanFactory owner) {
  3. // Don't override the class with CGLIB if no overrides.
  4. //这里我们没有方法重载,所以会进入这里
  5. if (!bd.hasMethodOverrides()) {
  6. Constructor<?> constructorToUse;
  7. synchronized (bd.constructorArgumentLock) {
  8. constructorToUse = (Constructor<?>) bd.resolvedConstructorOrFactoryMethod;
  9. if (constructorToUse == null) {
  10. final Class<?> clazz = bd.getBeanClass();
  11. if (clazz.isInterface()) {
  12. throw new BeanInstantiationException(clazz, "Specified class is an interface");
  13. }
  14. try {
  15. if (System.getSecurityManager() != null) {
  16. constructorToUse = AccessController.doPrivileged(
  17. (PrivilegedExceptionAction<Constructor<?>>) clazz::getDeclaredConstructor);
  18. }
  19. else {
  20. //获取默认的无参构造方法:public com.suibibk.spring.User()
  21. constructorToUse = clazz.getDeclaredConstructor();
  22. }
  23. bd.resolvedConstructorOrFactoryMethod = constructorToUse;
  24. }
  25. catch (Throwable ex) {
  26. throw new BeanInstantiationException(clazz, "No default constructor found", ex);
  27. }
  28. }
  29. }
  30. //这里去实例化
  31. return BeanUtils.instantiateClass(constructorToUse);
  32. }
  33. else {
  34. // Must generate CGLIB subclass.
  35. return instantiateWithMethodInjection(bd, beanName, owner);
  36. }
  37. }

点进真正去实例化的方法

  1. /**
  2. * Convenience method to instantiate a class using the given constructor.
  3. * <p>Note that this method tries to set the constructor accessible if given a
  4. * non-accessible (that is, non-public) constructor, and supports Kotlin classes
  5. * with optional parameters and default values.
  6. * @param ctor the constructor to instantiate
  7. * @param args the constructor arguments to apply (use {@code null} for an unspecified
  8. * parameter, Kotlin optional parameters and Java primitive types are supported)
  9. * @return the new instance
  10. * @throws BeanInstantiationException if the bean cannot be instantiated
  11. * @see Constructor#newInstance
  12. */
  13. public static <T> T instantiateClass(Constructor<T> ctor, Object... args) throws BeanInstantiationException {
  14. Assert.notNull(ctor, "Constructor must not be null");
  15. try {
  16. //设置构造方法可访问
  17. ReflectionUtils.makeAccessible(ctor);
  18. if (KotlinDetector.isKotlinReflectPresent() && KotlinDetector.isKotlinType(ctor.getDeclaringClass())) {
  19. return KotlinDelegate.instantiateClass(ctor, args);
  20. }
  21. else {
  22. //获取参数,我们这里用的是默认的方法,所以没有参数
  23. Class<?>[] parameterTypes = ctor.getParameterTypes();
  24. Assert.isTrue(args.length <= parameterTypes.length, "Can't specify more arguments than constructor parameters");
  25. Object[] argsWithDefaultValues = new Object[args.length];
  26. for (int i = 0 ; i < args.length; i++) {
  27. if (args[i] == null) {
  28. Class<?> parameterType = parameterTypes[i];
  29. argsWithDefaultValues[i] = (parameterType.isPrimitive() ? DEFAULT_TYPE_VALUES.get(parameterType) : null);
  30. }
  31. else {
  32. argsWithDefaultValues[i] = args[i];
  33. }
  34. }
  35. //用构造方法实例化对象
  36. return ctor.newInstance(argsWithDefaultValues);
  37. }
  38. }
  39. catch (InstantiationException ex) {
  40. throw new BeanInstantiationException(ctor, "Is it an abstract class?", ex);
  41. }
  42. catch (IllegalAccessException ex) {
  43. throw new BeanInstantiationException(ctor, "Is the constructor accessible?", ex);
  44. }
  45. catch (IllegalArgumentException ex) {
  46. throw new BeanInstantiationException(ctor, "Illegal arguments for constructor", ex);
  47. }
  48. catch (InvocationTargetException ex) {
  49. throw new BeanInstantiationException(ctor, "Constructor threw exception", ex.getTargetException());
  50. }
  51. }

终于,我们终于在

  1. return ctor.newInstance(argsWithDefaultValues);

这一行调用我们熟悉的构造方法来实例化了我们的类(额,话说这里完全没用什么代理啊,那为啥会有什么CglibSubclassingInstantiationStrategy,可能只是命名的问题吧),成功了,我们接下来看看还做了啥以及怎么把这个对象放进容器中的,放到容器中的什么位置,我们继续看下去。

在实例化完饭hi后我们继续后面执行了这一段代码

  1. BeanWrapper bw = new BeanWrapperImpl(beanInstance);
  2. initBeanWrapper(bw);
  3. return bw;

一开始把实例化的对象包装了下,包装成BeanWrapper对象。然后对该对象进行了一些初始化,返回,这里先不去探究为啥要对这里进行对象包装,反正大概就是包装一下然后赋予特殊的能力吧,我们看返回,继续回到上面的方法,这里直接列一下

  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. //这里初始化成了BeanWrapper对象
  9. if (instanceWrapper == null) {
  10. instanceWrapper = createBeanInstance(beanName, mbd, args);
  11. }
  12. //获取我们实例化后的对象
  13. Object bean = instanceWrapper.getWrappedInstance();
  14. //获取对象对应的类对象
  15. Class<?> beanType = instanceWrapper.getWrappedClass();
  16. if (beanType != NullBean.class) {
  17. mbd.resolvedTargetType = beanType;
  18. }
  19. // Allow post-processors to modify the merged bean definition.
  20. synchronized (mbd.postProcessingLock) {
  21. if (!mbd.postProcessed) {
  22. try {
  23. //调用一些合并的bean定义后处理器
  24. applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
  25. }
  26. catch (Throwable ex) {
  27. throw new BeanCreationException(mbd.getResourceDescription(), beanName,
  28. "Post-processing of merged bean definition failed", ex);
  29. }
  30. mbd.postProcessed = true;
  31. }
  32. }
  33. //急切地缓存单例以能够解析循环引用
  34. // Eagerly cache singletons to be able to resolve circular references
  35. // even when triggered by lifecycle interfaces like BeanFactoryAware.
  36. boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences &&
  37. isSingletonCurrentlyInCreation(beanName));
  38. if (earlySingletonExposure) {
  39. if (logger.isTraceEnabled()) {
  40. logger.trace("Eagerly caching bean '" + beanName +
  41. "' to allow for resolving potential circular references");
  42. }
  43. addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
  44. }
  45. // Initialize the bean instance.
  46. Object exposedObject = bean;
  47. try {
  48. populateBean(beanName, mbd, instanceWrapper);
  49. exposedObject = initializeBean(beanName, exposedObject, mbd);
  50. }
  51. catch (Throwable ex) {
  52. if (ex instanceof BeanCreationException && beanName.equals(((BeanCreationException) ex).getBeanName())) {
  53. throw (BeanCreationException) ex;
  54. }
  55. else {
  56. throw new BeanCreationException(
  57. mbd.getResourceDescription(), beanName, "Initialization of bean failed", ex);
  58. }
  59. }
  60. if (earlySingletonExposure) {
  61. Object earlySingletonReference = getSingleton(beanName, false);
  62. if (earlySingletonReference != null) {
  63. if (exposedObject == bean) {
  64. exposedObject = earlySingletonReference;
  65. }
  66. else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) {
  67. String[] dependentBeans = getDependentBeans(beanName);
  68. Set<String> actualDependentBeans = new LinkedHashSet<>(dependentBeans.length);
  69. for (String dependentBean : dependentBeans) {
  70. if (!removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) {
  71. actualDependentBeans.add(dependentBean);
  72. }
  73. }
  74. if (!actualDependentBeans.isEmpty()) {
  75. throw new BeanCurrentlyInCreationException(beanName,
  76. "Bean with name '" + beanName + "' has been injected into other beans [" +
  77. StringUtils.collectionToCommaDelimitedString(actualDependentBeans) +
  78. "] in its raw version as part of a circular reference, but has eventually been " +
  79. "wrapped. This means that said other beans do not use the final version of the " +
  80. "bean. This is often the result of over-eager type matching - consider using " +
  81. "'getBeanNamesForType' with the 'allowEagerInit' flag turned off, for example.");
  82. }
  83. }
  84. }
  85. }
  86. // Register bean as disposable.
  87. try {
  88. registerDisposableBeanIfNecessary(beanName, bean, mbd);
  89. }
  90. catch (BeanDefinitionValidationException ex) {
  91. throw new BeanCreationException(
  92. mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex);
  93. }
  94. return exposedObject;
  95. }

调用一些合并的bean定义后处理器

  1. applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);

做了啥

  1. /**
  2. * Apply MergedBeanDefinitionPostProcessors to the specified bean definition,
  3. * invoking their {@code postProcessMergedBeanDefinition} methods.
  4. * @param mbd the merged bean definition for the bean
  5. * @param beanType the actual type of the managed bean instance
  6. * @param beanName the name of the bean
  7. * @see MergedBeanDefinitionPostProcessor#postProcessMergedBeanDefinition
  8. */
  9. protected void applyMergedBeanDefinitionPostProcessors(RootBeanDefinition mbd, Class<?> beanType, String beanName) {
  10. for (BeanPostProcessor bp : getBeanPostProcessors()) {
  11. if (bp instanceof MergedBeanDefinitionPostProcessor) {
  12. MergedBeanDefinitionPostProcessor bdp = (MergedBeanDefinitionPostProcessor) bp;
  13. bdp.postProcessMergedBeanDefinition(mbd, beanType, beanName);
  14. }
  15. }
  16. }

这里就是对一些对象进行方法调用,我们看看是那些对象

  1. org.springframework.context.support.ApplicationContextAwareProcessor@303cf2ba
  2. org.springframework.context.annotation.ConfigurationClassPostProcessor$ImportAwareBeanPostProcessor@23e84203
  3. org.springframework.context.support.PostProcessorRegistrationDelegate$BeanPostProcessorChecker@19932c16
  4. com.suibibk.spring.MyBeanPostProcessors@73eb439a
  5. org.springframework.context.annotation.CommonAnnotationBeanPostProcessor@514646ef
  6. org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor@305ffe9e
  7. org.springframework.context.support.ApplicationListenerDetector@6e1567f1

都是一些PostProcessor,比如在this()里面看到过的CommonAnnotationBeanPostProcessor,但是我们这里只处理父类是MergedBeanDefinitionPostProcessor类的对象,这里ConfigurationClassPostProcessor是满足条件的,反正我们不需要去考虑具体有啥用,只要知道在这里先执行了这一批对象,如果我们新建一个类父类是MergedBeanDefinitionPostProcessor,也会在这里执行的。

急切地缓存单例以能够解析循环引用

  1. // Eagerly cache singletons to be able to resolve circular references
  2. // even when triggered by lifecycle interfaces like BeanFactoryAware.
  3. boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences &&
  4. isSingletonCurrentlyInCreation(beanName));

看注释的意思是在这里先缓存了该对象,然后就解决了循环依赖的问题,那应该解决循环依赖关键点就在这个代码里面吧,我们这里不研究先,只需要知道这回事就可以了,继续

  1. try {
  2. populateBean(beanName, mbd, instanceWrapper);
  3. exposedObject = initializeBean(beanName, exposedObject, mbd);
  4. }

我们先看populateBean(beanName, mbd, instanceWrapper);方法

  1. /**
  2. * Populate the bean instance in the given BeanWrapper with the property values
  3. * from the bean definition.
  4. * @param beanName the name of the bean
  5. * @param mbd the bean definition for the bean
  6. * @param bw the BeanWrapper with bean instance
  7. */
  8. @SuppressWarnings("deprecation") // for postProcessPropertyValues
  9. protected void populateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw) {
  10. //很明显我们的bw不为空,所以这个if里面的逻辑不会执行
  11. if (bw == null) {
  12. if (mbd.hasPropertyValues()) {
  13. throw new BeanCreationException(
  14. mbd.getResourceDescription(), beanName, "Cannot apply property values to null instance");
  15. }
  16. else {
  17. // Skip property population phase for null instance.
  18. return;
  19. }
  20. }
  21. //给任何InstantiationAwareBeanPostProcessors机会去修改
  22. //设置属性之前bean的状态。这可以用来,例如,
  23. //支持字段注入的样式。
  24. //这段代码其实就类似之前的MergedBeanDefinitionPostProcessor,反正会调用实现了InstantiationAwareBeanPostProcessor接口的那些类的postProcessAfterInstantiation方法。
  25. // Give any InstantiationAwareBeanPostProcessors the opportunity to modify the
  26. // state of the bean before properties are set. This can be used, for example,
  27. // to support styles of field injection.
  28. if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
  29. for (BeanPostProcessor bp : getBeanPostProcessors()) {
  30. if (bp instanceof InstantiationAwareBeanPostProcessor) {
  31. InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
  32. if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {
  33. return;
  34. }
  35. }
  36. }
  37. }
  38. PropertyValues pvs = (mbd.hasPropertyValues() ? mbd.getPropertyValues() : null);
  39. int resolvedAutowireMode = mbd.getResolvedAutowireMode();
  40. if (resolvedAutowireMode == AUTOWIRE_BY_NAME || resolvedAutowireMode == AUTOWIRE_BY_TYPE) {
  41. MutablePropertyValues newPvs = new MutablePropertyValues(pvs);
  42. // Add property values based on autowire by name if applicable.
  43. if (resolvedAutowireMode == AUTOWIRE_BY_NAME) {
  44. autowireByName(beanName, mbd, bw, newPvs);
  45. }
  46. // Add property values based on autowire by type if applicable.
  47. if (resolvedAutowireMode == AUTOWIRE_BY_TYPE) {
  48. autowireByType(beanName, mbd, bw, newPvs);
  49. }
  50. pvs = newPvs;
  51. }
  52. boolean hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors();
  53. boolean needsDepCheck = (mbd.getDependencyCheck() != AbstractBeanDefinition.DEPENDENCY_CHECK_NONE);
  54. PropertyDescriptor[] filteredPds = null;
  55. if (hasInstAwareBpps) {
  56. if (pvs == null) {
  57. pvs = mbd.getPropertyValues();
  58. }
  59. for (BeanPostProcessor bp : getBeanPostProcessors()) {
  60. if (bp instanceof InstantiationAwareBeanPostProcessor) {
  61. InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
  62. PropertyValues pvsToUse = ibp.postProcessProperties(pvs, bw.getWrappedInstance(), beanName);
  63. if (pvsToUse == null) {
  64. if (filteredPds == null) {
  65. filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
  66. }
  67. pvsToUse = ibp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName);
  68. if (pvsToUse == null) {
  69. return;
  70. }
  71. }
  72. pvs = pvsToUse;
  73. }
  74. }
  75. }
  76. if (needsDepCheck) {
  77. if (filteredPds == null) {
  78. filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
  79. }
  80. checkDependencies(beanName, mbd, filteredPds, pvs);
  81. }
  82. if (pvs != null) {
  83. applyPropertyValues(beanName, mbd, bw, pvs);
  84. }
  85. }

这个方法很长,我们先看注释:用属性值填充给定BeanWrapper中的bean实例,那这里应该也只是对bean进行增强吧,目前先跳过,我的目的只是找到什么时候把这个对象放到容器里,等研究相关依赖注入,AOP的时候再看看,毕竟现在看着些代码也不知干啥的,看不懂的说!我们继续看下面一行

  1. exposedObject = initializeBean(beanName, exposedObject, mbd);

这里又进行初始化

  1. /**
  2. * Initialize the given bean instance, applying factory callbacks
  3. * as well as init methods and bean post processors.
  4. * <p>Called from {@link #createBean} for traditionally defined beans,
  5. * and from {@link #initializeBean} for existing bean instances.
  6. * @param beanName the bean name in the factory (for debugging purposes)
  7. * @param bean the new bean instance we may need to initialize
  8. * @param mbd the bean definition that the bean was created with
  9. * (can also be {@code null}, if given an existing bean instance)
  10. * @return the initialized bean instance (potentially wrapped)
  11. * @see BeanNameAware
  12. * @see BeanClassLoaderAware
  13. * @see BeanFactoryAware
  14. * @see #applyBeanPostProcessorsBeforeInitialization
  15. * @see #invokeInitMethods
  16. * @see #applyBeanPostProcessorsAfterInitialization
  17. */
  18. protected Object initializeBean(String beanName, Object bean, @Nullable RootBeanDefinition mbd) {
  19. if (System.getSecurityManager() != null) {
  20. AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
  21. invokeAwareMethods(beanName, bean);
  22. return null;
  23. }, getAccessControlContext());
  24. }
  25. else {
  26. invokeAwareMethods(beanName, bean);
  27. }
  28. Object wrappedBean = bean;
  29. if (mbd == null || !mbd.isSynthetic()) {
  30. wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
  31. }
  32. try {
  33. invokeInitMethods(beanName, wrappedBean, mbd);
  34. }
  35. catch (Throwable ex) {
  36. throw new BeanCreationException(
  37. (mbd != null ? mbd.getResourceDescription() : null),
  38. beanName, "Invocation of init method failed", ex);
  39. }
  40. if (mbd == null || !mbd.isSynthetic()) {
  41. wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
  42. }
  43. return wrappedBean;
  44. }

只要是对一下方法进行工厂回调,这些代码就比较熟悉了,比如

  1. wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
  1. @Override
  2. public Object applyBeanPostProcessorsBeforeInitialization(Object existingBean, String beanName)
  3. throws BeansException {
  4. Object result = existingBean;
  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. }

这里直接调用postProcessBeforeInitialization(result, beanName);方法,这个是什么意思呢,比如我们在工作中经常会进行这样的定义

  1. @Component
  2. public class MyBeanPostProcessors implements BeanPostProcessor{
  3. public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
  4. System.out.println("MyBeanPostProcessors#postProcessBeforeInitialization:"+beanName);
  5. return bean;
  6. }
  7. public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
  8. System.out.println("MyBeanPostProcessors#postProcessAfterInitialization:"+beanName);
  9. return bean;
  10. }
  11. }

我们会发现没实例化一个bean就会先调用postProcessBeforeInitialization方法后调用postProcessAfterInitialization放方法,原理就是在上面实现的,让我们可以对这个bean进行修改增强。接着调用

  1. invokeInitMethods(beanName, wrappedBean, mbd);

看字面意思就大概知道是调用init-method方法,比如

  1. public class TestInitMethodAndDestroyMethod {
  2. @PostConstruct
  3. public void initMethod(){
  4. System.out.println("TestInitMethodAndDestroyMethod initMthod begin..");
  5. }
  6. public TestInitMethodAndDestroyMethod() {
  7. System.out.println("TestInitMethodAndDestroyMethod 实例化..");
  8. }
  9. @PreDestroy
  10. public void destroyMethod(){
  11. System.out.println("TestInitMethodAndDestroyMethod destroyMethod begin..");
  12. }

那这里就会先执行initMethod方法,这里也证明该方法是在构造方法后执行的。具体里面怎么执行的,这里暂不研究,继续

  1. wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);

这里就跟上面一样,执行的是

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

然后就返回了。额那什么时候放到容器中呢?原来我们之前放到缓存中就是放到容器中了,这里,我们看之前的方法

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

这里在执行完createBean创建完对象后会执行getSingleton方法

  1. /**
  2. * Return the (raw) singleton object registered under the given name,
  3. * creating and registering a new one if none registered yet.
  4. * @param beanName the name of the bean
  5. * @param singletonFactory the ObjectFactory to lazily create the singleton
  6. * with, if necessary
  7. * @return the registered singleton object
  8. */
  9. public Object getSingleton(String beanName, ObjectFactory<?> singletonFactory) {
  10. Assert.notNull(beanName, "Bean name must not be null");
  11. synchronized (this.singletonObjects) {
  12. Object singletonObject = this.singletonObjects.get(beanName);
  13. if (singletonObject == null) {
  14. if (this.singletonsCurrentlyInDestruction) {
  15. throw new BeanCreationNotAllowedException(beanName,
  16. "Singleton bean creation not allowed while singletons of this factory are in destruction " +
  17. "(Do not request a bean from a BeanFactory in a destroy method implementation!)");
  18. }
  19. if (logger.isDebugEnabled()) {
  20. logger.debug("Creating shared instance of singleton bean '" + beanName + "'");
  21. }
  22. beforeSingletonCreation(beanName);
  23. boolean newSingleton = false;
  24. boolean recordSuppressedExceptions = (this.suppressedExceptions == null);
  25. if (recordSuppressedExceptions) {
  26. this.suppressedExceptions = new LinkedHashSet<>();
  27. }
  28. try {
  29. singletonObject = singletonFactory.getObject();
  30. newSingleton = true;
  31. }
  32. catch (IllegalStateException ex) {
  33. // Has the singleton object implicitly appeared in the meantime ->
  34. // if yes, proceed with it since the exception indicates that state.
  35. singletonObject = this.singletonObjects.get(beanName);
  36. if (singletonObject == null) {
  37. throw ex;
  38. }
  39. }
  40. catch (BeanCreationException ex) {
  41. if (recordSuppressedExceptions) {
  42. for (Exception suppressedException : this.suppressedExceptions) {
  43. ex.addRelatedCause(suppressedException);
  44. }
  45. }
  46. throw ex;
  47. }
  48. finally {
  49. if (recordSuppressedExceptions) {
  50. this.suppressedExceptions = null;
  51. }
  52. afterSingletonCreation(beanName);
  53. }
  54. if (newSingleton) {
  55. addSingleton(beanName, singletonObject);
  56. }
  57. }
  58. return singletonObject;
  59. }
  60. }

这里看最后一段,如果是新的单例对象就加入

  1. if (newSingleton) {
  2. addSingleton(beanName, singletonObject);
  3. }
  1. protected void addSingleton(String beanName, Object singletonObject) {
  2. synchronized (this.singletonObjects) {
  3. //加入singletonObjects集合中
  4. this.singletonObjects.put(beanName, singletonObject);
  5. this.singletonFactories.remove(beanName);
  6. this.earlySingletonObjects.remove(beanName);
  7. this.registeredSingletons.add(beanName);
  8. }
  9. }

刚好对应之前获取的代码

  1. // Eagerly check singleton cache for manually registered singletons.
  2. Object sharedInstance = getSingleton(beanName);
  1. @Override
  2. @Nullable
  3. public Object getSingleton(String beanName) {
  4. return getSingleton(beanName, true);
  5. }
  1. @Nullable
  2. protected Object getSingleton(String beanName, boolean allowEarlyReference) {
  3. Object singletonObject = this.singletonObjects.get(beanName);
  4. if (singletonObject == null && isSingletonCurrentlyInCreation(beanName)) {
  5. synchronized (this.singletonObjects) {
  6. singletonObject = this.earlySingletonObjects.get(beanName);
  7. if (singletonObject == null && allowEarlyReference) {
  8. ObjectFactory<?> singletonFactory = this.singletonFactories.get(beanName);
  9. if (singletonFactory != null) {
  10. singletonObject = singletonFactory.getObject();
  11. this.earlySingletonObjects.put(beanName, singletonObject);
  12. this.singletonFactories.remove(beanName);
  13. }
  14. }
  15. }
  16. }
  17. return singletonObject;
  18. }

  1. Object singletonObject = this.singletonObjects.get(beanName);

如果在集合中就直接返回。完美!

基于猜测和不会的就跳过加调试的方式,终于跟完了主脉络源码,我快吐了,总结留在下一篇!

 183

啊!这个可能是世界上最丑的留言输入框功能~


当然,也是最丑的留言列表

有疑问发邮件到 : suibibk@qq.com 侵权立删
Copyright : 个人随笔   备案号 : 粤ICP备18099399号-2