个人随笔
目录
一个简单的例子来探寻Spring实例化bean执行源码的主脉络(二):解析配置类
2021-07-19 23:08:43

在上一篇文章中一个简单的例子来探寻Spring实例化bean执行源码的主脉络(一):this()方法,我们跟踪源码还是不知道怎么解析配置类,只是走完了this()方法,跟配置类感觉没有一毛钱的关系,这里我们大概了解了一下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

推测所有要加载为bean的类都将放到beanDefinitionMap中!

先在我们继续看看第二个方法register(componentClasses);

  1. public AnnotationConfigApplicationContext(Class<?>... componentClasses) {
  2. this();
  3. register(componentClasses);
  4. refresh();
  5. }

执行register(componentClasses);方法

这里我们终于看到了我们传入的参数,那大概可以推测,应该是在这个方法里面对我们的配置类进行初始化的,由上一篇文章我们可以合理推测,配置类也会放到beanDefinitionMap中,看看是不是这样,跟踪代码进去。

  1. /**
  2. * Register one or more component classes to be processed.
  3. * <p>Note that {@link #refresh()} must be called in order for the context
  4. * to fully process the new classes.
  5. * @param componentClasses one or more component classes — for example,
  6. * {@link Configuration @Configuration} classes
  7. * @see #scan(String...)
  8. * @see #refresh()
  9. */
  10. @Override
  11. public void register(Class<?>... componentClasses) {
  12. Assert.notEmpty(componentClasses, "At least one component class must be specified");
  13. this.reader.register(componentClasses);
  14. }

看注释说是注册一个或者多个要处理的组件类,大概猜测一下,这里应该是注册类,而不是生成bean,所以可能是解析配置类SpringConfiguration,然后解析配置类上的@ComponentScan(basePackages = “com.suibibk.spring”),然后把com.suibibk.spring文件加下的加了@Component注解的类全部都注册进来(猜测失败,值注册了SpringConfiguration),注册到哪里呢?大胆推测注册到DefaultListableBeanFactor的beanDefinitionMap中去,好让后面实例化bean,当然推测不一定正确,不过好的框架一定会有重充足的注释,我们一定要根据注释和变量命名来推测理解源码!这里然后u调用的是

  1. this.reader.register(componentClasses);

reader就是在this()方法里面初始化的AnnotationConfigApplicationContext对象的AnnotatedBeanDefinitionReader,继续跟进去

  1. public void register(Class<?>... componentClasses) {
  2. for (Class<?> componentClass : componentClasses) {
  3. registerBean(componentClass);
  4. }
  5. }

这里的意思是可能会传入多个配置类,然后循环处理所有的配置类调用registerBean(componentClass);方法,跟踪进去

  1. /**
  2. * Register a bean from the given bean class, deriving its metadata from
  3. * class-declared annotations.
  4. * @param beanClass the class of the bean
  5. */
  6. public void registerBean(Class<?> beanClass) {
  7. doRegisterBean(beanClass, null, null, null, null);
  8. }

方法的注释的意思是说从给定的bean类中注册一个bean,然后从类声名注解中得到他的元数据,是不是有点不知所云,不过大概可以知道还是解析配置类,继续跟进去

  1. private <T> void doRegisterBean(Class<T> beanClass, @Nullable String name,
  2. @Nullable Class<? extends Annotation>[] qualifiers, @Nullable Supplier<T> supplier,
  3. @Nullable BeanDefinitionCustomizer[] customizers) {
  4. AnnotatedGenericBeanDefinition abd = new AnnotatedGenericBeanDefinition(beanClass);
  5. if (this.conditionEvaluator.shouldSkip(abd.getMetadata())) {
  6. return;
  7. }
  8. abd.setInstanceSupplier(supplier);
  9. ScopeMetadata scopeMetadata = this.scopeMetadataResolver.resolveScopeMetadata(abd);
  10. abd.setScope(scopeMetadata.getScopeName());
  11. String beanName = (name != null ? name : this.beanNameGenerator.generateBeanName(abd, this.registry));
  12. AnnotationConfigUtils.processCommonDefinitionAnnotations(abd);
  13. if (qualifiers != null) {
  14. for (Class<? extends Annotation> qualifier : qualifiers) {
  15. if (Primary.class == qualifier) {
  16. abd.setPrimary(true);
  17. }
  18. else if (Lazy.class == qualifier) {
  19. abd.setLazyInit(true);
  20. }
  21. else {
  22. abd.addQualifier(new AutowireCandidateQualifier(qualifier));
  23. }
  24. }
  25. }
  26. if (customizers != null) {
  27. for (BeanDefinitionCustomizer customizer : customizers) {
  28. customizer.customize(abd);
  29. }
  30. }
  31. BeanDefinitionHolder definitionHolder = new BeanDefinitionHolder(abd, beanName);
  32. definitionHolder = AnnotationConfigUtils.applyScopedProxyMode(scopeMetadata, definitionHolder, this.registry);
  33. BeanDefinitionReaderUtils.registerBeanDefinition(definitionHolder, this.registry);
  34. }

我们先看第一行代码

  1. AnnotatedGenericBeanDefinition abd = new AnnotatedGenericBeanDefinition(beanClass);

这里相当于把我们传来的配置类包装了一下,变成了AnnotatedGenericBeanDefinition对象,话说,具体有啥用我也不知道,因为我们就只传了第一个参数beanClass,所以后面的qualifiers和customizers都是null,直接跳过,然后执行到最后的代码

  1. BeanDefinitionHolder definitionHolder = new BeanDefinitionHolder(abd, beanName);
  2. definitionHolder = AnnotationConfigUtils.applyScopedProxyMode(scopeMetadata, definitionHolder, this.registry);
  3. BeanDefinitionReaderUtils.registerBeanDefinition(definitionHolder, this.registry);

所料不差,就是把配置类注册到了DefaultListableBeanFactor的beanDefinitionMap中去,不过并没有对配置类的@ComponentScan进行解析,上面猜测失败,也就是说,register(componentClasses);方法只是对配置类进行了处理而已,其他啥都没有操作。

好吧,到这里我们已经看了this()和register(componentClasses)的源码,也知道了是在register注册了配置类,但是没有进行解析,看来一切都将在

  1. refresh();

中水落石出,走起!

执行refresh();方法

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

这个方法很长,我们一行行来分析,有些理解不了的就先跳过,毕竟我们只是为了找到主脉络,目的是知道spring在什么地方对配置类进行解析以及在什么地方进行初始化的。
先看第一行代码

  1. prepareRefresh();

准备刷新?

  1. /**
  2. * Prepare this context for refreshing, setting its startup date and
  3. * active flag as well as performing any initialization of property sources.
  4. */
  5. protected void prepareRefresh() {
  6. // Switch to active.
  7. this.startupDate = System.currentTimeMillis();
  8. this.closed.set(false);
  9. this.active.set(true);
  10. if (logger.isDebugEnabled()) {
  11. if (logger.isTraceEnabled()) {
  12. logger.trace("Refreshing " + this);
  13. }
  14. else {
  15. logger.debug("Refreshing " + getDisplayName());
  16. }
  17. }
  18. // Initialize any placeholder property sources in the context environment.
  19. initPropertySources();
  20. // Validate that all properties marked as required are resolvable:
  21. // see ConfigurablePropertyResolver#setRequiredProperties
  22. getEnvironment().validateRequiredProperties();
  23. // Store pre-refresh ApplicationListeners...
  24. if (this.earlyApplicationListeners == null) {
  25. this.earlyApplicationListeners = new LinkedHashSet<>(this.applicationListeners);
  26. }
  27. else {
  28. // Reset local application listeners to pre-refresh state.
  29. this.applicationListeners.clear();
  30. this.applicationListeners.addAll(this.earlyApplicationListeners);
  31. }
  32. // Allow for the collection of early ApplicationEvents,
  33. // to be published once the multicaster is available...
  34. this.earlyApplicationEvents = new LinkedHashSet<>();
  35. }

what?设置一些初始时间和活跃标志?大概浏览下应该是跟解析配置文件和初始bean什么的没有任何关系的,可以跳过!

咱们来看第二行代码

  1. // Tell the subclass to refresh the internal bean factory.
  2. ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();

告诉子类刷新内部的bean工厂,点进去看看

  1. protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
  2. refreshBeanFactory();
  3. return getBeanFactory();
  4. }
  1. @Override
  2. protected final void refreshBeanFactory() throws IllegalStateException {
  3. if (!this.refreshed.compareAndSet(false, true)) {
  4. throw new IllegalStateException(
  5. "GenericApplicationContext does not support multiple refresh attempts: just call 'refresh' once");
  6. }
  7. this.beanFactory.setSerializationId(getId());
  8. }

上面的代码是在GenericApplicationContext下,因为我们的AnnotationConfigApplicationContext继承的就是这个对象,这里只是简单的设置一些信息,我们再看 getBeanFactory()

  1. /**
  2. * Return the single internal BeanFactory held by this context
  3. * (as ConfigurableListableBeanFactory).
  4. */
  5. @Override
  6. public final ConfigurableListableBeanFactory getBeanFactory() {
  7. return this.beanFactory;
  8. }

只是返回一个BeanFactory由前面我们知道,这里就是DefaultListableBeanFactor对象。我们继续看代码

  1. // Prepare the bean factory for use in this context.
  2. prepareBeanFactory(beanFactory);

对这个beanFactory做一些准备工作,我们看看准备了啥

  1. /**
  2. * Configure the factory's standard context characteristics,
  3. * such as the context's ClassLoader and post-processors.
  4. * @param beanFactory the BeanFactory to configure
  5. */
  6. protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) {
  7. // Tell the internal bean factory to use the context's class loader etc.
  8. beanFactory.setBeanClassLoader(getClassLoader());
  9. beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader()));
  10. beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment()));
  11. // Configure the bean factory with context callbacks.
  12. beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));
  13. beanFactory.ignoreDependencyInterface(EnvironmentAware.class);
  14. beanFactory.ignoreDependencyInterface(EmbeddedValueResolverAware.class);
  15. beanFactory.ignoreDependencyInterface(ResourceLoaderAware.class);
  16. beanFactory.ignoreDependencyInterface(ApplicationEventPublisherAware.class);
  17. beanFactory.ignoreDependencyInterface(MessageSourceAware.class);
  18. beanFactory.ignoreDependencyInterface(ApplicationContextAware.class);
  19. // BeanFactory interface not registered as resolvable type in a plain factory.
  20. // MessageSource registered (and found for autowiring) as a bean.
  21. beanFactory.registerResolvableDependency(BeanFactory.class, beanFactory);
  22. beanFactory.registerResolvableDependency(ResourceLoader.class, this);
  23. beanFactory.registerResolvableDependency(ApplicationEventPublisher.class, this);
  24. beanFactory.registerResolvableDependency(ApplicationContext.class, this);
  25. // Register early post-processor for detecting inner beans as ApplicationListeners.
  26. beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(this));
  27. // Detect a LoadTimeWeaver and prepare for weaving, if found.
  28. if (beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
  29. beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
  30. // Set a temporary ClassLoader for type matching.
  31. beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
  32. }
  33. // Register default environment beans.
  34. if (!beanFactory.containsLocalBean(ENVIRONMENT_BEAN_NAME)) {
  35. beanFactory.registerSingleton(ENVIRONMENT_BEAN_NAME, getEnvironment());
  36. }
  37. if (!beanFactory.containsLocalBean(SYSTEM_PROPERTIES_BEAN_NAME)) {
  38. beanFactory.registerSingleton(SYSTEM_PROPERTIES_BEAN_NAME, getEnvironment().getSystemProperties());
  39. }
  40. if (!beanFactory.containsLocalBean(SYSTEM_ENVIRONMENT_BEAN_NAME)) {
  41. beanFactory.registerSingleton(SYSTEM_ENVIRONMENT_BEAN_NAME, getEnvironment().getSystemEnvironment());
  42. }
  43. }

一大串,对就是准备了一大串,看不懂没关系,反正我们知道是在做一些准备工作,我们看看有哪些看得懂的,比如beanFactory.setBeanClassLoader(getClassLoader());设置类加载器,

  1. beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));

加入一个Bean后置处理器,加入的是ApplicationContextAwareProcessor对象,我们知道前面在执行this()方法的时候也还加入了很多其它的后置处理器。其它的不看先,跟我的目标有区别,我是要找到什么地方解析配置类。我们看下一行

  1. // Allows post-processing of the bean factory in context subclasses.
  2. postProcessBeanFactory(beanFactory);

允许在上下文子类中对bean工厂进行后处理,点进去发现是一个空的方法,应该是模板方法为了让后面的子类实现然后对代码逻辑进行增强把。继续

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

在上下文中调用注册为bean的工厂处理器。额,看注释感觉是一个很重要的方法,难道一切都会在这里水落石出?

invokeBeanFactoryPostProcessors(beanFactory);方法

  1. /**
  2. * Instantiate and invoke all registered BeanFactoryPostProcessor beans,
  3. * respecting explicit order if given.
  4. * <p>Must be called before singleton instantiation.
  5. */
  6. protected void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory) {
  7. PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(beanFactory, getBeanFactoryPostProcessors());
  8. // Detect a LoadTimeWeaver and prepare for weaving, if found in the meantime
  9. // (e.g. through an @Bean method registered by ConfigurationClassPostProcessor)
  10. if (beanFactory.getTempClassLoader() == null && beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
  11. beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
  12. beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
  13. }
  14. }

实例化并调用所有注册的BeanFactoryPostProcessor,我们继续跟踪代码

  1. PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(beanFactory, getBeanFactoryPostProcessors());
  1. public static void invokeBeanFactoryPostProcessors(
  2. ConfigurableListableBeanFactory beanFactory, List<BeanFactoryPostProcessor> beanFactoryPostProcessors) {
  3. // Invoke BeanDefinitionRegistryPostProcessors first, if any.
  4. Set<String> processedBeans = new HashSet<>();
  5. if (beanFactory instanceof BeanDefinitionRegistry) {
  6. BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
  7. List<BeanFactoryPostProcessor> regularPostProcessors = new ArrayList<>();
  8. List<BeanDefinitionRegistryPostProcessor> registryProcessors = new ArrayList<>();
  9. for (BeanFactoryPostProcessor postProcessor : beanFactoryPostProcessors) {
  10. if (postProcessor instanceof BeanDefinitionRegistryPostProcessor) {
  11. BeanDefinitionRegistryPostProcessor registryProcessor =
  12. (BeanDefinitionRegistryPostProcessor) postProcessor;
  13. registryProcessor.postProcessBeanDefinitionRegistry(registry);
  14. registryProcessors.add(registryProcessor);
  15. }
  16. else {
  17. regularPostProcessors.add(postProcessor);
  18. }
  19. }
  20. // Do not initialize FactoryBeans here: We need to leave all regular beans
  21. // uninitialized to let the bean factory post-processors apply to them!
  22. // Separate between BeanDefinitionRegistryPostProcessors that implement
  23. // PriorityOrdered, Ordered, and the rest.
  24. List<BeanDefinitionRegistryPostProcessor> currentRegistryProcessors = new ArrayList<>();
  25. // First, invoke the BeanDefinitionRegistryPostProcessors that implement PriorityOrdered.
  26. String[] postProcessorNames =
  27. beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
  28. for (String ppName : postProcessorNames) {
  29. if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
  30. currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
  31. processedBeans.add(ppName);
  32. }
  33. }
  34. sortPostProcessors(currentRegistryProcessors, beanFactory);
  35. registryProcessors.addAll(currentRegistryProcessors);
  36. invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
  37. currentRegistryProcessors.clear();
  38. // Next, invoke the BeanDefinitionRegistryPostProcessors that implement Ordered.
  39. postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
  40. for (String ppName : postProcessorNames) {
  41. if (!processedBeans.contains(ppName) && beanFactory.isTypeMatch(ppName, Ordered.class)) {
  42. currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
  43. processedBeans.add(ppName);
  44. }
  45. }
  46. sortPostProcessors(currentRegistryProcessors, beanFactory);
  47. registryProcessors.addAll(currentRegistryProcessors);
  48. invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
  49. currentRegistryProcessors.clear();
  50. // Finally, invoke all other BeanDefinitionRegistryPostProcessors until no further ones appear.
  51. boolean reiterate = true;
  52. while (reiterate) {
  53. reiterate = false;
  54. postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
  55. for (String ppName : postProcessorNames) {
  56. if (!processedBeans.contains(ppName)) {
  57. currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
  58. processedBeans.add(ppName);
  59. reiterate = true;
  60. }
  61. }
  62. sortPostProcessors(currentRegistryProcessors, beanFactory);
  63. registryProcessors.addAll(currentRegistryProcessors);
  64. invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
  65. currentRegistryProcessors.clear();
  66. }
  67. // Now, invoke the postProcessBeanFactory callback of all processors handled so far.
  68. invokeBeanFactoryPostProcessors(registryProcessors, beanFactory);
  69. invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory);
  70. }
  71. else {
  72. // Invoke factory processors registered with the context instance.
  73. invokeBeanFactoryPostProcessors(beanFactoryPostProcessors, beanFactory);
  74. }
  75. // Do not initialize FactoryBeans here: We need to leave all regular beans
  76. // uninitialized to let the bean factory post-processors apply to them!
  77. String[] postProcessorNames =
  78. beanFactory.getBeanNamesForType(BeanFactoryPostProcessor.class, true, false);
  79. // Separate between BeanFactoryPostProcessors that implement PriorityOrdered,
  80. // Ordered, and the rest.
  81. List<BeanFactoryPostProcessor> priorityOrderedPostProcessors = new ArrayList<>();
  82. List<String> orderedPostProcessorNames = new ArrayList<>();
  83. List<String> nonOrderedPostProcessorNames = new ArrayList<>();
  84. for (String ppName : postProcessorNames) {
  85. if (processedBeans.contains(ppName)) {
  86. // skip - already processed in first phase above
  87. }
  88. else if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
  89. priorityOrderedPostProcessors.add(beanFactory.getBean(ppName, BeanFactoryPostProcessor.class));
  90. }
  91. else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
  92. orderedPostProcessorNames.add(ppName);
  93. }
  94. else {
  95. nonOrderedPostProcessorNames.add(ppName);
  96. }
  97. }
  98. // First, invoke the BeanFactoryPostProcessors that implement PriorityOrdered.
  99. sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
  100. invokeBeanFactoryPostProcessors(priorityOrderedPostProcessors, beanFactory);
  101. // Next, invoke the BeanFactoryPostProcessors that implement Ordered.
  102. List<BeanFactoryPostProcessor> orderedPostProcessors = new ArrayList<>(orderedPostProcessorNames.size());
  103. for (String postProcessorName : orderedPostProcessorNames) {
  104. orderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
  105. }
  106. sortPostProcessors(orderedPostProcessors, beanFactory);
  107. invokeBeanFactoryPostProcessors(orderedPostProcessors, beanFactory);
  108. // Finally, invoke all other BeanFactoryPostProcessors.
  109. List<BeanFactoryPostProcessor> nonOrderedPostProcessors = new ArrayList<>(nonOrderedPostProcessorNames.size());
  110. for (String postProcessorName : nonOrderedPostProcessorNames) {
  111. nonOrderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
  112. }
  113. invokeBeanFactoryPostProcessors(nonOrderedPostProcessors, beanFactory);
  114. // Clear cached merged bean definitions since the post-processors might have
  115. // modified the original metadata, e.g. replacing placeholders in values...
  116. beanFactory.clearMetadataCache();
  117. }

这个代码真的真的很长!我们根据方法的意思,大概可以看的出

  1. invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);

才是主要的,调用bean定义注册后置处理器,其它我们不看先,

  1. /**
  2. * Invoke the given BeanDefinitionRegistryPostProcessor beans.
  3. */
  4. private static void invokeBeanDefinitionRegistryPostProcessors(
  5. Collection<? extends BeanDefinitionRegistryPostProcessor> postProcessors, BeanDefinitionRegistry registry) {
  6. for (BeanDefinitionRegistryPostProcessor postProcessor : postProcessors) {
  7. postProcessor.postProcessBeanDefinitionRegistry(registry);
  8. }
  9. }

这里看不明白,继续

  1. /**
  2. * Derive further bean definitions from the configuration classes in the registry.
  3. */
  4. @Override
  5. public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) {
  6. int registryId = System.identityHashCode(registry);
  7. if (this.registriesPostProcessed.contains(registryId)) {
  8. throw new IllegalStateException(
  9. "postProcessBeanDefinitionRegistry already called on this post-processor against " + registry);
  10. }
  11. if (this.factoriesPostProcessed.contains(registryId)) {
  12. throw new IllegalStateException(
  13. "postProcessBeanFactory already called on this post-processor against " + registry);
  14. }
  15. this.registriesPostProcessed.add(registryId);
  16. processConfigBeanDefinitions(registry);
  17. }

从注册中心中的配置类派生进一步的bean定义,这里感觉有点苗头了,直接看

  1. processConfigBeanDefinitions(registry);
  1. /**
  2. * Build and validate a configuration model based on the registry of
  3. * {@link Configuration} classes.
  4. */
  5. public void processConfigBeanDefinitions(BeanDefinitionRegistry registry) {
  6. List<BeanDefinitionHolder> configCandidates = new ArrayList<>();
  7. String[] candidateNames = registry.getBeanDefinitionNames();
  8. for (String beanName : candidateNames) {
  9. BeanDefinition beanDef = registry.getBeanDefinition(beanName);
  10. if (beanDef.getAttribute(ConfigurationClassUtils.CONFIGURATION_CLASS_ATTRIBUTE) != null) {
  11. if (logger.isDebugEnabled()) {
  12. logger.debug("Bean definition has already been processed as a configuration class: " + beanDef);
  13. }
  14. }
  15. else if (ConfigurationClassUtils.checkConfigurationClassCandidate(beanDef, this.metadataReaderFactory)) {
  16. configCandidates.add(new BeanDefinitionHolder(beanDef, beanName));
  17. }
  18. }
  19. // Return immediately if no @Configuration classes were found
  20. if (configCandidates.isEmpty()) {
  21. return;
  22. }
  23. // Sort by previously determined @Order value, if applicable
  24. configCandidates.sort((bd1, bd2) -> {
  25. int i1 = ConfigurationClassUtils.getOrder(bd1.getBeanDefinition());
  26. int i2 = ConfigurationClassUtils.getOrder(bd2.getBeanDefinition());
  27. return Integer.compare(i1, i2);
  28. });
  29. // Detect any custom bean name generation strategy supplied through the enclosing application context
  30. SingletonBeanRegistry sbr = null;
  31. if (registry instanceof SingletonBeanRegistry) {
  32. sbr = (SingletonBeanRegistry) registry;
  33. if (!this.localBeanNameGeneratorSet) {
  34. BeanNameGenerator generator = (BeanNameGenerator) sbr.getSingleton(
  35. AnnotationConfigUtils.CONFIGURATION_BEAN_NAME_GENERATOR);
  36. if (generator != null) {
  37. this.componentScanBeanNameGenerator = generator;
  38. this.importBeanNameGenerator = generator;
  39. }
  40. }
  41. }
  42. if (this.environment == null) {
  43. this.environment = new StandardEnvironment();
  44. }
  45. // Parse each @Configuration class
  46. ConfigurationClassParser parser = new ConfigurationClassParser(
  47. this.metadataReaderFactory, this.problemReporter, this.environment,
  48. this.resourceLoader, this.componentScanBeanNameGenerator, registry);
  49. Set<BeanDefinitionHolder> candidates = new LinkedHashSet<>(configCandidates);
  50. Set<ConfigurationClass> alreadyParsed = new HashSet<>(configCandidates.size());
  51. do {
  52. parser.parse(candidates);
  53. parser.validate();
  54. Set<ConfigurationClass> configClasses = new LinkedHashSet<>(parser.getConfigurationClasses());
  55. configClasses.removeAll(alreadyParsed);
  56. // Read the model and create bean definitions based on its content
  57. if (this.reader == null) {
  58. this.reader = new ConfigurationClassBeanDefinitionReader(
  59. registry, this.sourceExtractor, this.resourceLoader, this.environment,
  60. this.importBeanNameGenerator, parser.getImportRegistry());
  61. }
  62. this.reader.loadBeanDefinitions(configClasses);
  63. alreadyParsed.addAll(configClasses);
  64. candidates.clear();
  65. if (registry.getBeanDefinitionCount() > candidateNames.length) {
  66. String[] newCandidateNames = registry.getBeanDefinitionNames();
  67. Set<String> oldCandidateNames = new HashSet<>(Arrays.asList(candidateNames));
  68. Set<String> alreadyParsedClasses = new HashSet<>();
  69. for (ConfigurationClass configurationClass : alreadyParsed) {
  70. alreadyParsedClasses.add(configurationClass.getMetadata().getClassName());
  71. }
  72. for (String candidateName : newCandidateNames) {
  73. if (!oldCandidateNames.contains(candidateName)) {
  74. BeanDefinition bd = registry.getBeanDefinition(candidateName);
  75. if (ConfigurationClassUtils.checkConfigurationClassCandidate(bd, this.metadataReaderFactory) &&
  76. !alreadyParsedClasses.contains(bd.getBeanClassName())) {
  77. candidates.add(new BeanDefinitionHolder(bd, candidateName));
  78. }
  79. }
  80. }
  81. candidateNames = newCandidateNames;
  82. }
  83. }
  84. while (!candidates.isEmpty());
  85. // Register the ImportRegistry as a bean in order to support ImportAware @Configuration classes
  86. if (sbr != null && !sbr.containsSingleton(IMPORT_REGISTRY_BEAN_NAME)) {
  87. sbr.registerSingleton(IMPORT_REGISTRY_BEAN_NAME, parser.getImportRegistry());
  88. }
  89. if (this.metadataReaderFactory instanceof CachingMetadataReaderFactory) {
  90. // Clear cache in externally provided MetadataReaderFactory; this is a no-op
  91. // for a shared cache since it'll be cleared by the ApplicationContext.
  92. ((CachingMetadataReaderFactory) this.metadataReaderFactory).clearCache();
  93. }
  94. }

构建和验证配置模型,
一开始

  1. List<BeanDefinitionHolder> configCandidates = new ArrayList<>();
  2. String[] candidateNames = registry.getBeanDefinitionNames();

从注册表中获取所有的候选名字

  1. @Override
  2. public String[] getBeanDefinitionNames() {
  3. String[] frozenNames = this.frozenBeanDefinitionNames;
  4. if (frozenNames != null) {
  5. return frozenNames.clone();
  6. }
  7. else {
  8. return StringUtils.toStringArray(this.beanDefinitionNames);
  9. }
  10. }

其实就是我们之前放进去的bean名称,再看后面的逻辑

  1. if (ConfigurationClassUtils.checkConfigurationClassCandidate(beanDef, this.metadataReaderFactory)) {
  2. configCandidates.add(new BeanDefinitionHolder(beanDef, beanName));
  3. }

看方法名字就大概知道是什么检查是否是配置类,也就是加了@Configuration注解的类,通过调试验证了我的猜想,最后configCandidates中只有com.suibibk.spring.SpringConfiguration的信息。

  1. // Parse each @Configuration class
  2. ConfigurationClassParser parser = new ConfigurationClassParser(
  3. this.metadataReaderFactory, this.problemReporter, this.environment,
  4. this.resourceLoader, this.componentScanBeanNameGenerator, registry);

这里生成了一个解析器,我们到这里就可以猜想,后面肯定是对配置类开始进行解析处理了,果不奇然

  1. do {
  2. parser.parse(candidates);
  3. parser.validate();
  4. ...

接下来就是要准备来解析了。感觉这里又是一个重大的方法。

parser.parse(candidates);方法

  1. ublic void parse(Set<BeanDefinitionHolder> configCandidates) {
  2. for (BeanDefinitionHolder holder : configCandidates) {
  3. BeanDefinition bd = holder.getBeanDefinition();
  4. try {
  5. if (bd instanceof AnnotatedBeanDefinition) {
  6. parse(((AnnotatedBeanDefinition) bd).getMetadata(), holder.getBeanName());
  7. }
  8. else if (bd instanceof AbstractBeanDefinition && ((AbstractBeanDefinition) bd).hasBeanClass()) {
  9. parse(((AbstractBeanDefinition) bd).getBeanClass(), holder.getBeanName());
  10. }
  11. else {
  12. parse(bd.getBeanClassName(), holder.getBeanName());
  13. }
  14. }
  15. catch (BeanDefinitionStoreException ex) {
  16. throw ex;
  17. }
  18. catch (Throwable ex) {
  19. throw new BeanDefinitionStoreException(
  20. "Failed to parse configuration class [" + bd.getBeanClassName() + "]", ex);
  21. }
  22. }
  23. this.deferredImportSelectorHandler.process();
  24. }

我们之前在注册配置类的时候开始有对配置类进行包装

  1. AnnotatedGenericBeanDefinition abd = new AnnotatedGenericBeanDefinition(beanClass);

而AnnotatedGenericBeanDefinition

  1. public class AnnotatedGenericBeanDefinition extends GenericBeanDefinition implements AnnotatedBeanDefinition

所以

  1. if (bd instanceof AnnotatedBeanDefinition)

为true。进入到第一个

  1. parse(((AnnotatedBeanDefinition) bd).getMetadata(), holder.getBeanName());

进行解析,参数为配置类的元数据和配置类名称

  1. protected final void parse(AnnotationMetadata metadata, String beanName) throws IOException {
  2. processConfigurationClass(new ConfigurationClass(metadata, beanName), DEFAULT_EXCLUSION_FILTER);
  3. }

继续跟进去

  1. protected void processConfigurationClass(ConfigurationClass configClass, Predicate<String> filter) throws IOException {
  2. if (this.conditionEvaluator.shouldSkip(configClass.getMetadata(), ConfigurationPhase.PARSE_CONFIGURATION)) {
  3. return;
  4. }
  5. ConfigurationClass existingClass = this.configurationClasses.get(configClass);
  6. if (existingClass != null) {
  7. if (configClass.isImported()) {
  8. if (existingClass.isImported()) {
  9. existingClass.mergeImportedBy(configClass);
  10. }
  11. // Otherwise ignore new imported config class; existing non-imported class overrides it.
  12. return;
  13. }
  14. else {
  15. // Explicit bean definition found, probably replacing an import.
  16. // Let's remove the old one and go with the new one.
  17. this.configurationClasses.remove(configClass);
  18. this.knownSuperclasses.values().removeIf(configClass::equals);
  19. }
  20. }
  21. // Recursively process the configuration class and its superclass hierarchy.
  22. SourceClass sourceClass = asSourceClass(configClass, filter);
  23. do {
  24. sourceClass = doProcessConfigurationClass(configClass, sourceClass, filter);
  25. }
  26. while (sourceClass != null);
  27. this.configurationClasses.put(configClass, configClass);
  28. }

这里调试发现existingClass为null,话说我们也没有对配置类进行任何特殊处理,所以应该是null,直接看下面的方法

  1. // Recursively process the configuration class and its superclass hierarchy.
  2. SourceClass sourceClass = asSourceClass(configClass, filter);

递归地处理配置类及其超类层次结构。我们这里就只有一个孤孤单单的配置类,所以这里面应该只有

  1. com.suibibk.spring.SpringConfiguration

话说这个方法是用于那种有注解上有注解或者继承类为配置类的情况吧,这里不考虑那么多先,直接看

  1. sourceClass = doProcessConfigurationClass(configClass, sourceClass, filter);
  1. /**
  2. * Apply processing and build a complete {@link ConfigurationClass} by reading the
  3. * annotations, members and methods from the source class. This method can be called
  4. * multiple times as relevant sources are discovered.
  5. * @param configClass the configuration class being build
  6. * @param sourceClass a source class
  7. * @return the superclass, or {@code null} if none found or previously processed
  8. */
  9. @Nullable
  10. protected final SourceClass doProcessConfigurationClass(
  11. ConfigurationClass configClass, SourceClass sourceClass, Predicate<String> filter)
  12. throws IOException {
  13. if (configClass.getMetadata().isAnnotated(Component.class.getName())) {
  14. // Recursively process any member (nested) classes first
  15. processMemberClasses(configClass, sourceClass, filter);
  16. }
  17. // Process any @PropertySource annotations
  18. for (AnnotationAttributes propertySource : AnnotationConfigUtils.attributesForRepeatable(
  19. sourceClass.getMetadata(), PropertySources.class,
  20. org.springframework.context.annotation.PropertySource.class)) {
  21. if (this.environment instanceof ConfigurableEnvironment) {
  22. processPropertySource(propertySource);
  23. }
  24. else {
  25. logger.info("Ignoring @PropertySource annotation on [" + sourceClass.getMetadata().getClassName() +
  26. "]. Reason: Environment must implement ConfigurableEnvironment");
  27. }
  28. }
  29. // Process any @ComponentScan annotations
  30. Set<AnnotationAttributes> componentScans = AnnotationConfigUtils.attributesForRepeatable(
  31. sourceClass.getMetadata(), ComponentScans.class, ComponentScan.class);
  32. if (!componentScans.isEmpty() &&
  33. !this.conditionEvaluator.shouldSkip(sourceClass.getMetadata(), ConfigurationPhase.REGISTER_BEAN)) {
  34. for (AnnotationAttributes componentScan : componentScans) {
  35. // The config class is annotated with @ComponentScan -> perform the scan immediately
  36. Set<BeanDefinitionHolder> scannedBeanDefinitions =
  37. this.componentScanParser.parse(componentScan, sourceClass.getMetadata().getClassName());
  38. // Check the set of scanned definitions for any further config classes and parse recursively if needed
  39. for (BeanDefinitionHolder holder : scannedBeanDefinitions) {
  40. BeanDefinition bdCand = holder.getBeanDefinition().getOriginatingBeanDefinition();
  41. if (bdCand == null) {
  42. bdCand = holder.getBeanDefinition();
  43. }
  44. if (ConfigurationClassUtils.checkConfigurationClassCandidate(bdCand, this.metadataReaderFactory)) {
  45. parse(bdCand.getBeanClassName(), holder.getBeanName());
  46. }
  47. }
  48. }
  49. }
  50. // Process any @Import annotations
  51. processImports(configClass, sourceClass, getImports(sourceClass), filter, true);
  52. // Process any @ImportResource annotations
  53. AnnotationAttributes importResource =
  54. AnnotationConfigUtils.attributesFor(sourceClass.getMetadata(), ImportResource.class);
  55. if (importResource != null) {
  56. String[] resources = importResource.getStringArray("locations");
  57. Class<? extends BeanDefinitionReader> readerClass = importResource.getClass("reader");
  58. for (String resource : resources) {
  59. String resolvedResource = this.environment.resolveRequiredPlaceholders(resource);
  60. configClass.addImportedResource(resolvedResource, readerClass);
  61. }
  62. }
  63. // Process individual @Bean methods
  64. Set<MethodMetadata> beanMethods = retrieveBeanMethodMetadata(sourceClass);
  65. for (MethodMetadata methodMetadata : beanMethods) {
  66. configClass.addBeanMethod(new BeanMethod(methodMetadata, configClass));
  67. }
  68. // Process default methods on interfaces
  69. processInterfaces(configClass, sourceClass);
  70. // Process superclass, if any
  71. if (sourceClass.getMetadata().hasSuperClass()) {
  72. String superclass = sourceClass.getMetadata().getSuperClassName();
  73. if (superclass != null && !superclass.startsWith("java") &&
  74. !this.knownSuperclasses.containsKey(superclass)) {
  75. this.knownSuperclasses.put(superclass, configClass);
  76. // Superclass found, return its annotation metadata and recurse
  77. return sourceClass.getSuperClass();
  78. }
  79. }
  80. // No superclass -> processing is complete
  81. return null;
  82. }

额又是常长的方法,不用怕,我们看下代码,发现有如下几处注释有点熟悉

  1. // Process any @PropertySource annotations
  2. // Process any @ComponentScan annotations
  3. // Process any @Import annotations
  4. // Process any @ImportResource annotations
  5. // Process individual @Bean methods
  6. / Process default methods on interfaces

我们一眼就看到了我们的目的 @ComponentScan 那其它我们就不看先。

  1. Set<AnnotationAttributes> componentScans = AnnotationConfigUtils.attributesForRepeatable(
  2. sourceClass.getMetadata(), ComponentScans.class, ComponentScan.class);
  3. if (!componentScans.isEmpty() &&
  4. !this.conditionEvaluator.shouldSkip(sourceClass.getMetadata(), ConfigurationPhase.REGISTER_BEAN)) {
  5. for (AnnotationAttributes componentScan : componentScans) {
  6. // The config class is annotated with @ComponentScan -> perform the scan immediately
  7. Set<BeanDefinitionHolder> scannedBeanDefinitions =
  8. this.componentScanParser.parse(componentScan, sourceClass.getMetadata().getClassName());
  9. // Check the set of scanned definitions for any further config classes and parse recursively if needed
  10. for (BeanDefinitionHolder holder : scannedBeanDefinitions) {
  11. BeanDefinition bdCand = holder.getBeanDefinition().getOriginatingBeanDefinition();
  12. if (bdCand == null) {
  13. bdCand = holder.getBeanDefinition();
  14. }
  15. if (ConfigurationClassUtils.checkConfigurationClassCandidate(bdCand, this.metadataReaderFactory)) {
  16. parse(bdCand.getBeanClassName(), holder.getBeanName());
  17. }
  18. }
  19. }
  20. }

开始先获取了componentScans注解信息,我们知道为

  1. basePackages=[com.suibibk.spring]

我们直接看代码

  1. // The config class is annotated with @ComponentScan -> perform the scan immediately
  2. Set<BeanDefinitionHolder> scannedBeanDefinitions =
  3. this.componentScanParser.parse(componentScan, sourceClass.getMetadata().getClassName());

这里解析该componentScan返回BeanDefinitionHolders,可以大胆的推测这个方法里面一定去扫描了com.suibibk.spring路径下面的所有类和子类,如果有@component注解则会解析为BeanDefinition注册到放到了DefaultListableBeanFactory中的beanDefinitionMap中,key为bean的名称,值为beanDefinition放的应该是这些类的相关类定义,其实我有点奇怪为啥这里还要返回,解析完就直接放到beanDefinitionMap中了啊。然后我看到了下面。

  1. for (BeanDefinitionHolder holder : scannedBeanDefinitions) {
  2. BeanDefinition bdCand = holder.getBeanDefinition().getOriginatingBeanDefinition();
  3. if (bdCand == null) {
  4. bdCand = holder.getBeanDefinition();
  5. }
  6. if (ConfigurationClassUtils.checkConfigurationClassCandidate(bdCand, this.metadataReaderFactory)) {
  7. parse(bdCand.getBeanClassName(), holder.getBeanName());
  8. }
  9. }

原来是怕解析出来的类有些也是配置类。

好了我们继续跟进去上面的parse方法去

  1. public Set<BeanDefinitionHolder> parse(AnnotationAttributes componentScan, final String declaringClass) {
  2. ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(this.registry,
  3. componentScan.getBoolean("useDefaultFilters"), this.environment, this.resourceLoader);
  4. Class<? extends BeanNameGenerator> generatorClass = componentScan.getClass("nameGenerator");
  5. boolean useInheritedGenerator = (BeanNameGenerator.class == generatorClass);
  6. scanner.setBeanNameGenerator(useInheritedGenerator ? this.beanNameGenerator :
  7. BeanUtils.instantiateClass(generatorClass));
  8. ScopedProxyMode scopedProxyMode = componentScan.getEnum("scopedProxy");
  9. if (scopedProxyMode != ScopedProxyMode.DEFAULT) {
  10. scanner.setScopedProxyMode(scopedProxyMode);
  11. }
  12. else {
  13. Class<? extends ScopeMetadataResolver> resolverClass = componentScan.getClass("scopeResolver");
  14. scanner.setScopeMetadataResolver(BeanUtils.instantiateClass(resolverClass));
  15. }
  16. scanner.setResourcePattern(componentScan.getString("resourcePattern"));
  17. for (AnnotationAttributes filter : componentScan.getAnnotationArray("includeFilters")) {
  18. for (TypeFilter typeFilter : typeFiltersFor(filter)) {
  19. scanner.addIncludeFilter(typeFilter);
  20. }
  21. }
  22. for (AnnotationAttributes filter : componentScan.getAnnotationArray("excludeFilters")) {
  23. for (TypeFilter typeFilter : typeFiltersFor(filter)) {
  24. scanner.addExcludeFilter(typeFilter);
  25. }
  26. }
  27. boolean lazyInit = componentScan.getBoolean("lazyInit");
  28. if (lazyInit) {
  29. scanner.getBeanDefinitionDefaults().setLazyInit(true);
  30. }
  31. Set<String> basePackages = new LinkedHashSet<>();
  32. String[] basePackagesArray = componentScan.getStringArray("basePackages");
  33. for (String pkg : basePackagesArray) {
  34. String[] tokenized = StringUtils.tokenizeToStringArray(this.environment.resolvePlaceholders(pkg),
  35. ConfigurableApplicationContext.CONFIG_LOCATION_DELIMITERS);
  36. Collections.addAll(basePackages, tokenized);
  37. }
  38. for (Class<?> clazz : componentScan.getClassArray("basePackageClasses")) {
  39. basePackages.add(ClassUtils.getPackageName(clazz));
  40. }
  41. if (basePackages.isEmpty()) {
  42. basePackages.add(ClassUtils.getPackageName(declaringClass));
  43. }
  44. scanner.addExcludeFilter(new AbstractTypeHierarchyTraversingFilter(false, false) {
  45. @Override
  46. protected boolean matchClassName(String className) {
  47. return declaringClass.equals(className);
  48. }
  49. });
  50. return scanner.doScan(StringUtils.toStringArray(basePackages));
  51. }

其实这个前面都不用看,扫描一样就发现了最重要的代码

  1. return scanner.doScan(StringUtils.toStringArray(basePackages));

话说,spring习惯把最终要执行的代码方法名称以do开头。

  1. /**
  2. * Perform a scan within the specified base packages,
  3. * returning the registered bean definitions.
  4. * <p>This method does <i>not</i> register an annotation config processor
  5. * but rather leaves this up to the caller.
  6. * @param basePackages the packages to check for annotated classes
  7. * @return set of beans registered if any for tooling registration purposes (never {@code null})
  8. */
  9. protected Set<BeanDefinitionHolder> doScan(String... basePackages) {
  10. Assert.notEmpty(basePackages, "At least one base package must be specified");
  11. Set<BeanDefinitionHolder> beanDefinitions = new LinkedHashSet<>();
  12. for (String basePackage : basePackages) {
  13. Set<BeanDefinition> candidates = findCandidateComponents(basePackage);
  14. for (BeanDefinition candidate : candidates) {
  15. ScopeMetadata scopeMetadata = this.scopeMetadataResolver.resolveScopeMetadata(candidate);
  16. candidate.setScope(scopeMetadata.getScopeName());
  17. String beanName = this.beanNameGenerator.generateBeanName(candidate, this.registry);
  18. if (candidate instanceof AbstractBeanDefinition) {
  19. postProcessBeanDefinition((AbstractBeanDefinition) candidate, beanName);
  20. }
  21. if (candidate instanceof AnnotatedBeanDefinition) {
  22. AnnotationConfigUtils.processCommonDefinitionAnnotations((AnnotatedBeanDefinition) candidate);
  23. }
  24. if (checkCandidate(beanName, candidate)) {
  25. BeanDefinitionHolder definitionHolder = new BeanDefinitionHolder(candidate, beanName);
  26. definitionHolder =
  27. AnnotationConfigUtils.applyScopedProxyMode(scopeMetadata, definitionHolder, this.registry);
  28. beanDefinitions.add(definitionHolder);
  29. registerBeanDefinition(definitionHolder, this.registry);
  30. }
  31. }
  32. }

我们看这一行

  1. Set<BeanDefinition> candidates = findCandidateComponents(basePackage);

这里直接就根据包路径返回了所有的BeanDefinition,所以这里绝bi是一行关键代码,后面就直接遍历candidates注册到DefaultListableBeanFactory中了,这个我们在this()方法里面注册一些后置处理器的时候看过,这里就不多说。

  1. /**
  2. * Scan the class path for candidate components.
  3. * @param basePackage the package to check for annotated classes
  4. * @return a corresponding Set of autodetected bean definitions
  5. */
  6. public Set<BeanDefinition> findCandidateComponents(String basePackage) {
  7. if (this.componentsIndex != null && indexSupportsIncludeFilters()) {
  8. return addCandidateComponentsFromIndex(this.componentsIndex, basePackage);
  9. }
  10. else {
  11. return scanCandidateComponents(basePackage);
  12. }
  13. }

扫描类路径,寻找候选组件。
直接看

  1. return scanCandidateComponents(basePackage);

不要问我为啥不看

  1. return addCandidateComponentsFromIndex(this.componentsIndex, basePackage);

额,按直觉来说我就不会选择它,看源码不要想着一下就全部弄明白,要靠直觉和大胆的推测以及略过看不懂的先再辅助于调试就可以了。

  1. private Set<BeanDefinition> scanCandidateComponents(String basePackage) {
  2. Set<BeanDefinition> candidates = new LinkedHashSet<>();
  3. try {
  4. //拼接路径,这里是:classpath*:com/suibibk/spring/**/*.class
  5. String packageSearchPath = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX +
  6. resolveBasePackage(basePackage) + '/' + this.resourcePattern;
  7. //根据路径获得资源
  8. Resource[] resources = getResourcePatternResolver().getResources(packageSearchPath);
  9. boolean traceEnabled = logger.isTraceEnabled();
  10. boolean debugEnabled = logger.isDebugEnabled();
  11. for (Resource resource : resources) {
  12. if (traceEnabled) {
  13. logger.trace("Scanning " + resource);
  14. }
  15. if (resource.isReadable()) {
  16. try {
  17. MetadataReader metadataReader = getMetadataReaderFactory().getMetadataReader(resource);
  18. //判断是否是候选Component,也就是加了@Component注解的类
  19. if (isCandidateComponent(metadataReader)) {
  20. //是的化这里就创建BeanDefinition
  21. ScannedGenericBeanDefinition sbd = new ScannedGenericBeanDefinition(metadataReader);
  22. sbd.setSource(resource);
  23. if (isCandidateComponent(sbd)) {
  24. if (debugEnabled) {
  25. logger.debug("Identified candidate component class: " + resource);
  26. }
  27. //加入到集合中
  28. candidates.add(sbd);
  29. }
  30. else {
  31. if (debugEnabled) {
  32. logger.debug("Ignored because not a concrete top-level class: " + resource);
  33. }
  34. }
  35. }
  36. else {
  37. if (traceEnabled) {
  38. logger.trace("Ignored because not matching any filter: " + resource);
  39. }
  40. }
  41. }
  42. catch (Throwable ex) {
  43. throw new BeanDefinitionStoreException(
  44. "Failed to read candidate component class: " + resource, ex);
  45. }
  46. }
  47. else {
  48. if (traceEnabled) {
  49. logger.trace("Ignored because not readable: " + resource);
  50. }
  51. }
  52. }
  53. }
  54. catch (IOException ex) {
  55. throw new BeanDefinitionStoreException("I/O failure during classpath scanning", ex);
  56. }
  57. //返回
  58. return candidates;
  59. }

大概过程是
1、拼接路径获得包扫描真实的路径
2、获得资源集合
3、遍历资源获得可读的元标签数据
4、判断是否是候选的组件
5、如果是候选的组件则生成BeanDefinition加入集合中
6、返回候选集合。

到这里终于把配置类解析完了。接下来就是上面说的,循环遍历候选集合注册到DefaultListableBeanFactory的beanDefinitionMap中。

  1. registerBeanDefinition(definitionHolder, this.registry);

关键点总结:

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

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

 180

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


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

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