BeanFactoryPostProcessor和BeanDefinitionPostProcessor和ApplicationListener
BeanDefinitionPostProcessor: Spring的接口类用于处理对Bean的定义注册
GenericBeanDefinition:用于定义Bean的信息
FactoryBean: 用于处理Bean工厂的类

一:Spring是如何发布事件的? ApplicationListener

1.1)自己写一个TulingApplicationListener 实现ApplicationListener接口,并且把该组件加入到容器中.

  1. /**
  2. * 创建一个监听器
  3. *
  4. */
  5. @Component
  6. public class TulingApplicationListener implements ApplicationListener {
  7. @Override
  8. public void onApplicationEvent(ApplicationEvent event) {
  9. System.out.println("TulingApplicationListener 接受到了一个事件"+event);
  10. }
  11. }
  1. public class MainClass {
  2. public static void main(String[] args) {
  3. AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(MainConfig.class);
  4. ctx.publishEvent(new ApplicationEvent("我手动发布了一个事件") {
  5. @Override
  6. public Object getSource() {
  7. return super.getSource();
  8. }
  9. });
  10. ctx.close();
  11. }
  12. }

测试结果:

  1. TulingApplicationListener 接受到了一个事件org.springframework.context.event.ContextRefreshedEvent[source=org.springframework.context.annotation.AnnotationConfigApplicationContext@37bba400: startup date [Mon May 27 21:42:51 CST 2019]; root of context hierarchy]
  2. TulingApplicationListener 接受到了一个事件com.tuling.testapplicationlistener.MainClass$1[source=我手动发布了一个事件]
  3. TulingApplicationListener 接受到了一个事件org.springframework.context.event.ContextClosedEvent[source=org.springframework.context.annotation.AnnotationConfigApplicationContext@37bba400: startup date [Mon May 27 21:42:51 CST 2019]; root of context hierarchy]

进入类AnnotationConfigApplicationContext的构造函数

  1. /**
  2. * Create a new AnnotationConfigApplicationContext that needs to be populated
  3. * through {@link #register} calls and then manually {@linkplain #refresh refreshed}.
  4. */
  5. public AnnotationConfigApplicationContext() {
  6. // 往容器中放入一些列的后置处理器
  7. this.reader = new AnnotatedBeanDefinitionReader(this);
  8. // 指定扫描策略
  9. this.scanner = new ClassPathBeanDefinitionScanner(this);
  10. }
  11. /**
  12. * Create a new AnnotationConfigApplicationContext, deriving bean definitions
  13. * from the given annotated classes and automatically refreshing the context.
  14. * @param annotatedClasses one or more annotated classes,
  15. * e.g. {@link Configuration @Configuration} classes
  16. */
  17. public AnnotationConfigApplicationContext(Class<?>... annotatedClasses) {
  18. this();
  19. // 把配置类注册容器中【把我们的MainConfig记录到容器中去】
  20. register(annotatedClasses);
  21. //容器刷新。极其重要,核心
  22. refresh();
  23. }

如下图,在执行到this.scanner = new ClassPathBeanDefinitionScanner(this);时,容器中会有六个默认的bean

image.png

而走完register(annotatedClasses);之后,会将我们的MainConfig(自己定义的组件)记录到容器中去

  1. @Configuration
  2. @ComponentScan(basePackages = "com.tuling.testbeanfacotoryPostProcessor")
  3. public class MainConfig {
  4. }

image.png
如下为AbstractApplicationContext.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. // 调用bean工厂的后置处理器
  15. invokeBeanFactoryPostProcessors(beanFactory);
  16. // Register bean processors that intercept bean creation.
  17. registerBeanPostProcessors(beanFactory);
  18. // Initialize message source for this context.
  19. initMessageSource();
  20. // Initialize event multicaster for this context.
  21. // 初始化事件多播器
  22. initApplicationEventMulticaster();
  23. // Initialize other special beans in specific context subclasses.
  24. onRefresh();
  25. // Check for listener beans and register them.
  26. // 把事件监听器注册到多播器上去
  27. registerListeners();
  28. // Instantiate all remaining (non-lazy-init) singletons.
  29. finishBeanFactoryInitialization(beanFactory);
  30. // Last step: publish corresponding event.
  31. finishRefresh();
  32. }
  33. catch (BeansException ex) {
  34. if (logger.isWarnEnabled()) {
  35. logger.warn("Exception encountered during context initialization - " +
  36. "cancelling refresh attempt: " + ex);
  37. }
  38. // Destroy already created singletons to avoid dangling resources.
  39. destroyBeans();
  40. // Reset 'active' flag.
  41. cancelRefresh(ex);
  42. // Propagate exception to caller.
  43. throw ex;
  44. }
  45. finally {
  46. // Reset common introspection caches in Spring's core, since we
  47. // might not ever need metadata for singleton beans anymore...
  48. resetCommonCaches();
  49. }
  50. }
  51. }

源码解析:

i1>org.springframework.context.support.AbstractApplicationContext#refresh
i2>org.springframework.context.support.AbstractApplicationContext#initApplicationEventMulticaster(初始化事件多播器)
i3>org.springframework.context.support.AbstractApplicationContext#registerListeners(把事件监听器注册到多播器上去)


i2(初始化事件多播器源码解析)

AbstractApplicationContext.initApplicationEventMulticaster()

  1. protected void initApplicationEventMulticaster() {
  2. ConfigurableListableBeanFactory beanFactory = getBeanFactory();
  3. //判断IOC容器中包含applicationEventMulticaster 事件多播器的Bean的name
  4. if (beanFactory.containsLocalBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME)) {
  5. //创建一个applicationEventMulticaster的bean放在IOC 容器中,bean的name 为applicationEventMulticaster
  6. this.applicationEventMulticaster =beanFactory.getBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, ApplicationEventMulticaster.class);
  7. if (logger.isDebugEnabled()) {
  8. logger.debug("Using ApplicationEventMulticaster [" + this.applicationEventMulticaster + "]");
  9. }
  10. }
  11. //容器中不包含一个beanName 为applicationEventMulticaster的多播器组件
  12. else {
  13. //创建一个SimpleApplicationEventMulticaster 多播器
  14. this.applicationEventMulticaster = new SimpleApplicationEventMulticaster(beanFactory);
  15. //注册到容器中
  16. beanFactory.registerSingleton(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, this.applicationEventMulticaster);
  17. if (logger.isDebugEnabled()) {
  18. logger.debug("Unable to locate ApplicationEventMulticaster with name '" +
  19. APPLICATION_EVENT_MULTICASTER_BEAN_NAME +
  20. "': using default [" + this.applicationEventMulticaster + "]");
  21. }
  22. }
  23. }

i3:把容器中的监听器注册到多播器上去 源码解析

AbstractApplicationContext.registerListeners()

  1. protected void registerListeners() {
  2. //去容器中把applicationListener 捞取出来注册到多播器上去(系统的)
  3. for (ApplicationListener<?> listener : getApplicationListeners()) {
  4. getApplicationEventMulticaster().addApplicationListener(listener);
  5. }
  6. //我们自己实现了ApplicationListener 的组件
  7. String[] listenerBeanNames = getBeanNamesForType(ApplicationListener.class, true, false);
  8. for (String listenerBeanName : listenerBeanNames) {
  9. getApplicationEventMulticaster().addApplicationListenerBean(listenerBeanName);
  10. }
  11. //在这里之前,我们早期想发布的事件 由于没有多播器没有发布,
  12. 在这里我们总算有了自己的多播器,可以在这里发布早期堆积的事件了.
  13. Set<ApplicationEvent> earlyEventsToProcess = this.earlyApplicationEvents;
  14. this.earlyApplicationEvents = null;
  15. // 如果拥有早期待处理事件,调用多播器,并通知观察者
  16. if (earlyEventsToProcess != null) {
  17. for (ApplicationEvent earlyEvent : earlyEventsToProcess) {
  18. // 通知观察者
  19. getApplicationEventMulticaster().multicastEvent(earlyEvent);
  20. }
  21. }
  22. }

在看一眼AbstractApplicationContext.refresh()方法,多播器的早期与后期界线点为:AbstractApplicationContext.registerListeners();
在运行查看源码的时候发现没有早期事件,先存起来,程序过了registerListeners()后在 AbstractApplicationContext.finishRefresh();里面进行出发;其原因是因为防止onRefresh()中有事件[SpringBoot启动调用tomcat]

  1. ------------------------------如何发布事件------------------------------------------------------
  2. public void multicastEvent(final ApplicationEvent event, ResolvableType eventType) {
  3. ResolvableType type = (eventType != null ? eventType : resolveDefaultEventType(event));
  4. //获取到所有的监听器
  5. for (final ApplicationListener<?> listener : getApplicationListeners(event, type)) {
  6. //看spring 容器中是否支持线程池 异步发送事件
  7. Executor executor = getTaskExecutor();
  8. if (executor != null) {
  9. executor.execute(new Runnable() {
  10. @Override
  11. public void run() {
  12. invokeListener(listener, event);
  13. }
  14. });
  15. }
  16. else { //同步发送事件
  17. invokeListener(listener, event);
  18. }
  19. }
  20. }
  21. private void doInvokeListener(ApplicationListener listener, ApplicationEvent event) {
  22. try {
  23. //调用对于listener的onApplicationEvent事件
  24. listener.onApplicationEvent(event);
  25. }
  26. catch (ClassCastException ex) {
  27. String msg = ex.getMessage();
  28. if (msg == null || matchesClassCastMessage(msg, event.getClass())) {
  29. // Possibly a lambda-defined listener which we could not resolve the generic event type for
  30. // -> let's suppress the exception and just log a debug message.
  31. Log logger = LogFactory.getLog(getClass());
  32. if (logger.isDebugEnabled()) {
  33. logger.debug("Non-matching event type for listener: " + listener, ex);
  34. }
  35. }
  36. else {
  37. throw ex;
  38. }
  39. }
  40. }

二:BeanDefinitionRegistryPostProcessor 的处理源码流程

执行时机:所有的bean定义信息将要被加载到容器中,Bean实例还没有被初始化。

  1. @Component
  2. public class TulingBeanDefinationRegisterPostProcessor implements BeanDefinitionRegistryPostProcessor {
  3. @Override
  4. public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
  5. System.out.println("TulingBeanDefinationRegisterPostProcessor的postProcessBeanDefinitionRegistry方法");
  6. System.out.println("bean定义的数据量:"+registry.getBeanDefinitionCount());
  7. RootBeanDefinition rootBeanDefinition = new RootBeanDefinition(TulingLog.class);
  8. registry.registerBeanDefinition("tulingLog",rootBeanDefinition);
  9. }
  10. @Override
  11. public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
  12. System.out.println("TulingBeanDefinationRegisterPostProcessor的postProcessBeanFactory方法");
  13. System.out.println(beanFactory.getBeanDefinitionCount());
  14. }
  15. }

三:BeanFactoryPostProcessor 处理流程

执行时间:所有的Bean定义信息已经加载到容器中,但是Bean实例还没有被初始化.

  1. @Component
  2. public class TulingBeanFactoryPostProcessor implements BeanFactoryPostProcessor {
  3. @Override
  4. public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
  5. System.out.println("IOC 容器调用了TulingBeanFactoryPostProcessor的postProcessBeanFactory方法");
  6. for(String name:beanFactory.getBeanDefinitionNames()) {
  7. if("tulingLog".equals(name)) {
  8. BeanDefinition beanDefinition = beanFactory.getBeanDefinition(name);
  9. beanDefinition.setLazyInit(true);
  10. }
  11. }
  12. }
  13. }

调用链:
i1:org.springframework.context.support.AbstractApplicationContext#refresh
>i2:org.springframework.context.support.AbstractApplicationContext#invokeBeanFactoryPostProcessors
>i3:org.springframework.context.support.PostProcessorRegistrationDelegate#invokeBeanFactoryPostProcessors
>i4:org.springframework.context.support.PostProcessorRegistrationDelegate#invokeBeanDefinitionRegistryPostProcessors
>i5:org.springframework.context.annotation.ConfigurationClassPostProcessor#processConfigBeanDefinitions
> i6:org.springframework.context.annotation.ConfigurationClassParser#parse
>i7:org.springframework.context.annotation.ConfigurationClassParser#processConfigurationClass
>i8:org.springframework.context.annotation.ConfigurationClassParser#doProcessConfigurationClass

i4标记处源码解析 #invokeBeanFactoryPostProcessors

org.springframework.context.support.
PostProcessorRegistrationDelegate#invokeBeanFactoryPostProcessors

  1. public static void invokeBeanFactoryPostProcessors(
  2. ConfigurableListableBeanFactory beanFactory, List<BeanFactoryPostProcessor> beanFactoryPostProcessors) {
  3. // Invoke BeanDefinitionRegistryPostProcessors first, if any.
  4. Set<String> processedBeans = new HashSet<String>();
  5. //判断IOC 容器是不是BeanDefinitionRegistry的?
  6. if (beanFactory instanceof BeanDefinitionRegistry) {
  7. //把IOC容器 强制转为BeanDefinitionRegistry类型的
  8. BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
  9. //创建一个普通的PostProcessors的list的组件
  10. List<BeanFactoryPostProcessor> regularPostProcessors = new LinkedList<BeanFactoryPostProcessor>();
  11. //创建一个BeanDefinitionRegistryPostProcessor类型的list
  12. List<BeanDefinitionRegistryPostProcessor> registryProcessors = new LinkedList<BeanDefinitionRegistryPostProcessor>();
  13. //处理容器硬编码(new 出来的)带入的beanFacotryPostProcessors
  14. for (BeanFactoryPostProcessor postProcessor : beanFactoryPostProcessors) {
  15. //判断是不是BeanDefinitionRegistryPostProcessor
  16. if (postProcessor instanceof BeanDefinitionRegistryPostProcessor) {
  17. BeanDefinitionRegistryPostProcessor registryProcessor =
  18. (BeanDefinitionRegistryPostProcessor) postProcessor;
  19. //调用BeanDefinitionRegistryPostProcessor的postProcessBeanDefinitionRegistry
  20. registryProcessor.postProcessBeanDefinitionRegistry(registry);
  21. //加入到list集合中
  22. registryProcessors.add(registryProcessor);
  23. }
  24. else {//判断不是BeanDefinitionRegistryPostProcessor
  25. //加入到集合中
  26. regularPostProcessors.add(postProcessor);
  27. }
  28. }
  29. //创建一个当前注册的RegistryProcessors的集合
  30. List<BeanDefinitionRegistryPostProcessor> currentRegistryProcessors = new ArrayList<BeanDefinitionRegistryPostProcessor>();
  31. 第一步:去容器中查询是否有BeanDefinitionRegistryPostProcessor类型的
  32. String[] postProcessorNames =
  33. beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
  34. for (String ppName : postProcessorNames) {
  35. //判断是不是实现了PriorityOrdered接口的
  36. if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
  37. //添加到currentRegistryProcessors的集合中
  38. currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
  39. //添加到processedBeans的集合中
  40. processedBeans.add(ppName);
  41. }
  42. }
  43. //进行排序
  44. sortPostProcessors(currentRegistryProcessors, beanFactory);
  45. registryProcessors.addAll(currentRegistryProcessors);
  46. //调用BeanDefinitionRegistryPostProcessors的postProcessBeanDefinitionRegistry方法
  47. invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
  48. currentRegistryProcessors.clear();
  49. // Next, invoke the BeanDefinitionRegistryPostProcessors that implement Ordered.
  50. 第二步:去容器中查询是否有BeanDefinitionRegistryPostProcessor类型的
  51. for (String ppName : postProcessorNames) {
  52. //排除被处理过的,并且实现了Ordered接口的
  53. if (!processedBeans.contains(ppName) && beanFactory.isTypeMatch(ppName, Ordered.class)) {
  54. currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
  55. //加到以处理的list中
  56. processedBeans.add(ppName);
  57. }
  58. }
  59. sortPostProcessors(currentRegistryProcessors, beanFactory);
  60. registryProcessors.addAll(currentRegistryProcessors);
  61. //调用BeanDefinitionRegistryPostProcessors的postProcessBeanDefinitionRegistry方法
  62. invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
  63. currentRegistryProcessors.clear();
  64. //调用普通的BeanDefinitionRegistryPostProcessors没用实现 PriorithOrdered和Ordered接口
  65. boolean reiterate = true;
  66. while (reiterate) {
  67. reiterate = false;
  68. postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
  69. for (String ppName : postProcessorNames) {
  70. if (!processedBeans.contains(ppName)) {
  71. currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
  72. processedBeans.add(ppName);
  73. reiterate = true;
  74. }
  75. }
  76. sortPostProcessors(currentRegistryProcessors, beanFactory);
  77. registryProcessors.addAll(currentRegistryProcessors);
  78. invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
  79. currentRegistryProcessors.clear();
  80. }
  81. //调用上诉实现了也实现了BeanFactoryPostProcessors的接口
  82. invokeBeanFactoryPostProcessors(registryProcessors, beanFactory);
  83. invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory);
  84. }
  85. else {
  86. // Invoke factory processors registered with the context instance.
  87. invokeBeanFactoryPostProcessors(beanFactoryPostProcessors, beanFactory);
  88. }
  89. //去IOC 容器中获取BeanFactoryPostProcessor 类型的
  90. String[] postProcessorNames =
  91. beanFactory.getBeanNamesForType(BeanFactoryPostProcessor.class, true, false);
  92. //分离实现了PriorityOrdered接口的 Ordered 接口的 普通的
  93. List<BeanFactoryPostProcessor> priorityOrderedPostProcessors = new ArrayList<BeanFactoryPostProcessor>();
  94. List<String> orderedPostProcessorNames = new ArrayList<String>();
  95. List<String> nonOrderedPostProcessorNames = new ArrayList<String>();
  96. for (String ppName : postProcessorNames) {
  97. if (processedBeans.contains(ppName)) {
  98. // skip - already processed in first phase above
  99. }
  100. else if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
  101. priorityOrderedPostProcessors.add(beanFactory.getBean(ppName, BeanFactoryPostProcessor.class));
  102. }
  103. else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
  104. orderedPostProcessorNames.add(ppName);
  105. }
  106. else {
  107. nonOrderedPostProcessorNames.add(ppName);
  108. }
  109. }
  110. 调用 PriorityOrdered.
  111. sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
  112. invokeBeanFactoryPostProcessors(priorityOrderedPostProcessors, beanFactory);
  113. //调用 Ordered.
  114. List<BeanFactoryPostProcessor> orderedPostProcessors = new ArrayList<BeanFactoryPostProcessor>();
  115. for (String postProcessorName : orderedPostProcessorNames) {
  116. orderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
  117. }
  118. sortPostProcessors(orderedPostProcessors, beanFactory);
  119. invokeBeanFactoryPostProcessors(orderedPostProcessors, beanFactory);
  120. //调用普通的
  121. List<BeanFactoryPostProcessor> nonOrderedPostProcessors = new ArrayList<BeanFactoryPostProcessor>();
  122. for (String postProcessorName : nonOrderedPostProcessorNames) {
  123. nonOrderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
  124. }
  125. invokeBeanFactoryPostProcessors(nonOrderedPostProcessors, beanFactory);
  126. // Clear cached merged bean definitions since the post-processors might have
  127. // modified the original metadata, e.g. replacing placeholders in values...
  128. beanFactory.clearMetadataCache();
  129. }

i5源码解析

i5:org.springframework.context.annotation.
ConfigurationClassPostProcessor#processConfigBeanDefinitions

  1. public void processConfigBeanDefinitions(BeanDefinitionRegistry registry) {
  2. List<BeanDefinitionHolder> configCandidates = new ArrayList<BeanDefinitionHolder>();
  3. //去IOC容器中的获取Bean定义的名称
  4. // private volatile List<String> beanDefinitionNames = new ArrayList<String>(256);
  5. //没有解析之前,系统候选的bean定义配置(有自己的 有系统自带的)
  6. String[] candidateNames = registry.getBeanDefinitionNames();
  7. //循环Bean定义的名称 找出自己的传入的主配置类的bean定义信息 configCandidates
  8. for (String beanName : candidateNames) {
  9. //去bean定义的map中获取对应的Bean定义对象
  10. // private final Map<String, BeanDefinition> beanDefinitionMap = new ConcurrentHashMap<String, BeanDefinition>(256);
  11. BeanDefinition beanDef = registry.getBeanDefinition(beanName);
  12. //检查该bean定义对象是不是用来描述配置类
  13. if (ConfigurationClassUtils.isFullConfigurationClass(beanDef) ||
  14. ConfigurationClassUtils.isLiteConfigurationClass(beanDef)) {
  15. if (logger.isDebugEnabled()) {
  16. logger.debug("Bean definition has already been processed as a configuration class: " + beanDef);
  17. }
  18. }
  19. else if (ConfigurationClassUtils.checkConfigurationClassCandidate(beanDef, this.metadataReaderFactory)) {
  20. configCandidates.add(new BeanDefinitionHolder(beanDef, beanName));
  21. }
  22. }
  23. // Return immediately if no @Configuration classes were found
  24. if (configCandidates.isEmpty()) {
  25. return;
  26. }
  27. //检查配置类排序,看哪一个先起作用
  28. Collections.sort(configCandidates, new Comparator<BeanDefinitionHolder>() {
  29. @Override
  30. public int compare(BeanDefinitionHolder bd1, BeanDefinitionHolder bd2) {
  31. int i1 = ConfigurationClassUtils.getOrder(bd1.getBeanDefinition());
  32. int i2 = ConfigurationClassUtils.getOrder(bd2.getBeanDefinition());
  33. return (i1 < i2) ? -1 : (i1 > i2) ? 1 : 0;
  34. }
  35. });
  36. // bean的名称生成策略
  37. SingletonBeanRegistry sbr = null;
  38. if (registry instanceof SingletonBeanRegistry) {
  39. sbr = (SingletonBeanRegistry) registry;
  40. if (!this.localBeanNameGeneratorSet && sbr.containsSingleton(CONFIGURATION_BEAN_NAME_GENERATOR)) {
  41. BeanNameGenerator generator = (BeanNameGenerator) sbr.getSingleton(CONFIGURATION_BEAN_NAME_GENERATOR);
  42. // 扫描包组件生成器
  43. this.componentScanBeanNameGenerator = generator;
  44. // importBean生成器
  45. this.importBeanNameGenerator = generator;
  46. }
  47. }
  48. /***创建一个配置类解析器
  49. 1)元数据读取器工厂
  50. this.metadataReaderFactory = metadataReaderFactory;
  51. 2)问题报告器
  52. this.problemReporter = problemReporter;
  53. //设置环境
  54. this.environment = environment;
  55. 3)资源加载器
  56. this.resourceLoader = resourceLoader;
  57. 4)创建了一个组件扫描器
  58. this.componentScanParser = new ComponentScanAnnotationParser(
  59. environment, resourceLoader, componentScanBeanNameGenerator, registry);
  60. this.conditionEvaluator = new ConditionEvaluator(registry, environment, resourceLoader);
  61. ****/
  62. // 创建配置类解析器
  63. ConfigurationClassParser parser = new ConfigurationClassParser(
  64. this.metadataReaderFactory, this.problemReporter, this.environment,
  65. this.resourceLoader, this.componentScanBeanNameGenerator, registry);
  66. //将要被解析的配置类(把自己的configCandidates加入到 候选的)
  67. Set<BeanDefinitionHolder> candidates = new LinkedHashSet<BeanDefinitionHolder>(configCandidates);
  68. //已经被解析的配置类(由于do while 那么mainclass就一定会被解析,被解析的size为1)
  69. Set<ConfigurationClass> alreadyParsed = new HashSet<ConfigurationClass>(configCandidates.size());
  70. do {
  71. //通过配置解析器真正的解析配置类
  72. parser.parse(candidates);
  73. //进行校验
  74. parser.validate();
  75. //获取ConfigClass (把解析过的配置bean定义信息获取出来)
  76. Set<ConfigurationClass> configClasses = new LinkedHashSet<ConfigurationClass>(parser.getConfigurationClasses());
  77. configClasses.removeAll(alreadyParsed);
  78. // Read the model and create bean definitions based on its content
  79. if (this.reader == null) {
  80. this.reader = new ConfigurationClassBeanDefinitionReader(
  81. registry, this.sourceExtractor, this.resourceLoader, this.environment,
  82. this.importBeanNameGenerator, parser.getImportRegistry());
  83. }
  84. //@CompentScan是直接注册Bean定义信息的 但是通过获取@Import,@Bean这种的注解还没有注册的bean定义,
  85. this.reader.loadBeanDefinitions(configClasses);
  86. //把系统解析过我们自己的组件放在alreadyParsed
  87. alreadyParsed.addAll(configClasses);
  88. //清除解析过的 配置文件
  89. candidates.clear();
  90. //已经注册的bean定义个数大于最新 开始系统+主配置类的(发生过解析)
  91. if (registry.getBeanDefinitionCount() > candidateNames.length) {
  92. //获取系统+自己解析的+mainconfig的bean定义信息
  93. String[] newCandidateNames = registry.getBeanDefinitionNames();
  94. //系统的+mainconfig的bean定义信息
  95. Set<String> oldCandidateNames = new HashSet<String>(Arrays.asList(candidateNames));
  96. //已经解析过的自己的组件
  97. Set<String> alreadyParsedClasses = new HashSet<String>();
  98. for (ConfigurationClass configurationClass : alreadyParsed) {
  99. alreadyParsedClasses.add(configurationClass.getMetadata().getClassName());
  100. }
  101. for (String candidateName : newCandidateNames) {
  102. //老的(系统+mainconfig) 不包含解析的
  103. if (!oldCandidateNames.contains(candidateName)) {
  104. //把当前bean定义获取出来
  105. BeanDefinition bd = registry.getBeanDefinition(candidateName);
  106. //检查是否为解析过的
  107. if (ConfigurationClassUtils.checkConfigurationClassCandidate(bd, this.metadataReaderFactory) &&
  108. !alreadyParsedClasses.contains(bd.getBeanClassName())) {
  109. //若不是解析过且通过检查的 把当前的bean定义 加入到candidates中
  110. candidates.add(new BeanDefinitionHolder(bd, candidateName));
  111. }
  112. }
  113. }
  114. 把解析过的赋值给原来的
  115. candidateNames = newCandidateNames;
  116. }
  117. }
  118. while (!candidates.isEmpty()); //还存主没有解析过的 再次解析
  119. // Register the ImportRegistry as a bean in order to support ImportAware @Configuration classes
  120. if (sbr != null) {
  121. if (!sbr.containsSingleton(IMPORT_REGISTRY_BEAN_NAME)) {
  122. sbr.registerSingleton(IMPORT_REGISTRY_BEAN_NAME, parser.getImportRegistry());
  123. }
  124. }
  125. if (this.metadataReaderFactory instanceof CachingMetadataReaderFactory) {
  126. ((CachingMetadataReaderFactory) this.metadataReaderFactory).clearCache();
  127. }
  128. }

i6源码解析

org.springframework.context.annotation.
ConfigurationClassParser#parse

  1. public void parse(Set<BeanDefinitionHolder> configCandidates) {
  2. this.deferredImportSelectors = new LinkedList<DeferredImportSelectorHolder>();
  3. for (BeanDefinitionHolder holder : configCandidates) {
  4. BeanDefinition bd = holder.getBeanDefinition();
  5. try {
  6. //注解形式的bean定义信息
  7. if (bd instanceof AnnotatedBeanDefinition) {
  8. //解析配置类的bean定义
  9. parse(((AnnotatedBeanDefinition) bd).getMetadata(), holder.getBeanName());
  10. }
  11. else if (bd instanceof AbstractBeanDefinition && ((AbstractBeanDefinition) bd).hasBeanClass()) {
  12. parse(((AbstractBeanDefinition) bd).getBeanClass(), holder.getBeanName());
  13. }
  14. else {
  15. parse(bd.getBeanClassName(), holder.getBeanName());
  16. }
  17. }
  18. catch (BeanDefinitionStoreException ex) {
  19. throw ex;
  20. }
  21. catch (Throwable ex) {
  22. throw new BeanDefinitionStoreException(
  23. "Failed to parse configuration class [" + bd.getBeanClassName() + "]", ex);
  24. }
  25. }
  26. processDeferredImportSelectors();
  27. }
  28. org.springframework.context.annotation.ConfigurationClassParser#parse
  29. org.springframework.context.annotation.ConfigurationClassParser#processConfigurationClass
  30. protected void processConfigurationClass(ConfigurationClass configClass) throws IOException {
  31. if (this.conditionEvaluator.shouldSkip(configClass.getMetadata(), ConfigurationPhase.PARSE_CONFIGURATION)) {
  32. return;
  33. }
  34. ConfigurationClass existingClass = this.configurationClasses.get(configClass);
  35. if (existingClass != null) {
  36. if (configClass.isImported()) {
  37. if (existingClass.isImported()) {
  38. existingClass.mergeImportedBy(configClass);
  39. }
  40. // Otherwise ignore new imported config class; existing non-imported class overrides it.
  41. return;
  42. }
  43. else {
  44. // Explicit bean definition found, probably replacing an import.
  45. // Let's remove the old one and go with the new one.
  46. this.configurationClasses.remove(configClass);
  47. for (Iterator<ConfigurationClass> it = this.knownSuperclasses.values().iterator(); it.hasNext();) {
  48. if (configClass.equals(it.next())) {
  49. it.remove();
  50. }
  51. }
  52. }
  53. }
  54. 递归处理配置类及其超类层次结构。
  55. SourceClass sourceClass = asSourceClass(configClass);
  56. do {
  57. sourceClass = doProcessConfigurationClass(configClass, sourceClass);
  58. }
  59. while (sourceClass != null);
  60. this.configurationClasses.put(configClass, configClass);
  61. }
  62. org.springframework.context.annotation.ConfigurationClassParser#doProcessConfigurationClass
  63. protected final SourceClass doProcessConfigurationClass(ConfigurationClass configClass, SourceClass sourceClass)
  64. throws IOException {
  65. // Recursively process any member (nested) classes first
  66. processMemberClasses(configClass, sourceClass);
  67. //处理@PropertySource注解
  68. for (AnnotationAttributes propertySource : AnnotationConfigUtils.attributesForRepeatable(
  69. sourceClass.getMetadata(), PropertySources.class,
  70. org.springframework.context.annotation.PropertySource.class)) {
  71. if (this.environment instanceof ConfigurableEnvironment) {
  72. processPropertySource(propertySource);
  73. }
  74. else {
  75. logger.warn("Ignoring @PropertySource annotation on [" + sourceClass.getMetadata().getClassName() +
  76. "]. Reason: Environment must implement ConfigurableEnvironment");
  77. }
  78. }
  79. //处理@ComponentScan注解
  80. //解析@ComponentScans注解的属性 封装成一个一个的componentscan对象
  81. Set<AnnotationAttributes> componentScans = AnnotationConfigUtils.attributesForRepeatable(sourceClass.getMetadata(), ComponentScans.class, ComponentScan.class);
  82. if (!componentScans.isEmpty() &&!this.conditionEvaluator.shouldSkip(sourceClass.getMetadata(), ConfigurationPhase.REGISTER_BEAN)) {
  83. //循环componentScans的set
  84. for (AnnotationAttributes componentScan : componentScans) {
  85. // 立即执行扫描解析
  86. Set<BeanDefinitionHolder> scannedBeanDefinitions =this.componentScanParser.parse(componentScan, sourceClass.getMetadata().getClassName());
  87. //检查任何其他配置类的扫描定义集,并在需要时递归解析
  88. for (BeanDefinitionHolder holder : scannedBeanDefinitions) {
  89. //获取原始的bean定义信息
  90. BeanDefinition bdCand = holder.getBeanDefinition().getOriginatingBeanDefinition();
  91. if (bdCand == null) {
  92. bdCand = holder.getBeanDefinition();
  93. }
  94. //检查当前的bean定义信息是不是配置类 比如MainConfig的bean定义信息
  95. if (ConfigurationClassUtils.checkConfigurationClassCandidate(bdCand, this.metadataReaderFactory)) {
  96. //递归调用来解析MainConfig,解析出来配置类的中导入的bean定义信息
  97. parse(bdCand.getBeanClassName(), holder.getBeanName());
  98. }
  99. }
  100. }
  101. }
  102. //处理@Import注解 解析Import 注解的ImportSelector ImportBeanDefinitionRegister,@Bean这种
  103. //存放在ConfigClass中
  104. processImports(configClass, sourceClass, getImports(sourceClass), true);
  105. //处理 @ImportResource annotations
  106. if (sourceClass.getMetadata().isAnnotated(ImportResource.class.getName())) {
  107. AnnotationAttributes importResource =
  108. AnnotationConfigUtils.attributesFor(sourceClass.getMetadata(), ImportResource.class);
  109. String[] resources = importResource.getStringArray("locations");
  110. Class<? extends BeanDefinitionReader> readerClass = importResource.getClass("reader");
  111. for (String resource : resources) {
  112. String resolvedResource = this.environment.resolveRequiredPlaceholders(resource);
  113. configClass.addImportedResource(resolvedResource, readerClass);
  114. }
  115. }
  116. // 处理 @Bean methods
  117. Set<MethodMetadata> beanMethods = retrieveBeanMethodMetadata(sourceClass);
  118. for (MethodMetadata methodMetadata : beanMethods) {
  119. configClass.addBeanMethod(new BeanMethod(methodMetadata, configClass));
  120. }
  121. //处理接口
  122. processInterfaces(configClass, sourceClass);
  123. // 处理超类的
  124. if (sourceClass.getMetadata().hasSuperClass()) {
  125. String superclass = sourceClass.getMetadata().getSuperClassName();
  126. if (!superclass.startsWith("java") && !this.knownSuperclasses.containsKey(superclass)) {
  127. this.knownSuperclasses.put(superclass, configClass);
  128. // Superclass found, return its annotation metadata and recurse
  129. return sourceClass.getSuperClass();
  130. }
  131. }
  132. // No superclass -> processing is complete
  133. return null;
  134. }
  135. //通过组件扫描器进行真正的解析
  136. org.springframework.context.annotation.ComponentScanAnnotationParser#parse
  137. Set<BeanDefinitionHolder>
  138. public Set<BeanDefinitionHolder> parse(AnnotationAttributes componentScan, final String declaringClass) {
  139. Assert.state(this.environment != null, "Environment must not be null");
  140. Assert.state(this.resourceLoader != null, "ResourceLoader must not be null");
  141. //创建一个类路径下的bean定义扫描器
  142. ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(this.registry,
  143. componentScan.getBoolean("useDefaultFilters"), this.environment, this.resourceLoader);
  144. //为扫描器设置一个bean 名称的生成器
  145. Class<? extends BeanNameGenerator> generatorClass = componentScan.getClass("nameGenerator");
  146. boolean useInheritedGenerator = (BeanNameGenerator.class == generatorClass);
  147. scanner.setBeanNameGenerator(useInheritedGenerator ? this.beanNameGenerator :
  148. BeanUtils.instantiateClass(generatorClass));
  149. ScopedProxyMode scopedProxyMode = componentScan.getEnum("scopedProxy");
  150. if (scopedProxyMode != ScopedProxyMode.DEFAULT) {
  151. scanner.setScopedProxyMode(scopedProxyMode);
  152. }
  153. else {
  154. Class<? extends ScopeMetadataResolver> resolverClass = componentScan.getClass("scopeResolver");
  155. scanner.setScopeMetadataResolver(BeanUtils.instantiateClass(resolverClass));
  156. }
  157. scanner.setResourcePattern(componentScan.getString("resourcePattern"));
  158. for (AnnotationAttributes filter : componentScan.getAnnotationArray("includeFilters")) {
  159. for (TypeFilter typeFilter : typeFiltersFor(filter)) {
  160. scanner.addIncludeFilter(typeFilter);
  161. }
  162. }
  163. for (AnnotationAttributes filter : componentScan.getAnnotationArray("excludeFilters")) {
  164. for (TypeFilter typeFilter : typeFiltersFor(filter)) {
  165. scanner.addExcludeFilter(typeFilter);
  166. }
  167. }
  168. boolean lazyInit = componentScan.getBoolean("lazyInit");
  169. if (lazyInit) {
  170. scanner.getBeanDefinitionDefaults().setLazyInit(true);
  171. }
  172. Set<String> basePackages = new LinkedHashSet<String>();
  173. String[] basePackagesArray = componentScan.getStringArray("basePackages");
  174. for (String pkg : basePackagesArray) {
  175. String[] tokenized = StringUtils.tokenizeToStringArray(this.environment.resolvePlaceholders(pkg),
  176. ConfigurableApplicationContext.CONFIG_LOCATION_DELIMITERS);
  177. basePackages.addAll(Arrays.asList(tokenized));
  178. }
  179. for (Class<?> clazz : componentScan.getClassArray("basePackageClasses")) {
  180. basePackages.add(ClassUtils.getPackageName(clazz));
  181. }
  182. if (basePackages.isEmpty()) {
  183. basePackages.add(ClassUtils.getPackageName(declaringClass));
  184. }
  185. scanner.addExcludeFilter(new AbstractTypeHierarchyTraversingFilter(false, false) {
  186. @Override
  187. protected boolean matchClassName(String className) {
  188. return declaringClass.equals(className);
  189. }
  190. });
  191. //真正扫描器扫描指定路径
  192. return scanner.doScan(StringUtils.toStringArray(basePackages));
  193. }
  194. //创建类路径下的bean定义扫描器
  195. public ClassPathBeanDefinitionScanner(BeanDefinitionRegistry registry, boolean useDefaultFilters,
  196. Environment environment, ResourceLoader resourceLoader) {
  197. Assert.notNull(registry, "BeanDefinitionRegistry must not be null");
  198. this.registry = registry;
  199. //使用默认的扫描规则
  200. if (useDefaultFilters) {
  201. registerDefaultFilters();
  202. }
  203. //设置环境变量
  204. setEnvironment(environment);
  205. //设置资源加载器
  206. setResourceLoader(resourceLoader);
  207. }
  208. //默认的扫描规则
  209. protected void registerDefaultFilters() {
  210. //添加了Componet的解析,这就是我们为啥@Componet @Respository @Service @Controller的 @AspectJ
  211. this.includeFilters.add(new AnnotationTypeFilter(Component.class));
  212. ClassLoader cl = ClassPathScanningCandidateComponentProvider.class.getClassLoader();
  213. try {
  214. //添加Jsr 250规范的注解
  215. this.includeFilters.add(new AnnotationTypeFilter(
  216. ((Class<? extends Annotation>) ClassUtils.forName("javax.annotation.ManagedBean", cl)), false));
  217. logger.debug("JSR-250 'javax.annotation.ManagedBean' found and supported for component scanning");
  218. }
  219. catch (ClassNotFoundException ex) {
  220. // JSR-250 1.1 API (as included in Java EE 6) not available - simply skip.
  221. }
  222. try {
  223. //JSR330的注解
  224. this.includeFilters.add(new AnnotationTypeFilter(
  225. ((Class<? extends Annotation>) ClassUtils.forName("javax.inject.Named", cl)), false));
  226. logger.debug("JSR-330 'javax.inject.Named' annotation found and supported for component scanning");
  227. }
  228. catch (ClassNotFoundException ex) {
  229. // JSR-330 API not available - simply skip.
  230. }
  231. }
  232. 使用扫描器去真正的扫描类,返回Set<BeanDefinitionHolder>
  233. org.springframework.context.annotation.ClassPathBeanDefinitionScanner#doScan
  234. protected Set<BeanDefinitionHolder> doScan(String... basePackages) {
  235. Assert.notEmpty(basePackages, "At least one base package must be specified");
  236. //创建一个Bean定义 holder的 set
  237. Set<BeanDefinitionHolder> beanDefinitions = new LinkedHashSet<BeanDefinitionHolder>();
  238. //循环扫描路径
  239. for (String basePackage : basePackages) {
  240. //找到候选的组件集合
  241. Set<BeanDefinition> candidates = findCandidateComponents(basePackage);
  242. //循环候选组件集合
  243. for (BeanDefinition candidate : candidates) {
  244. ScopeMetadata scopeMetadata = this.scopeMetadataResolver.resolveScopeMetadata(candidate);
  245. candidate.setScope(scopeMetadata.getScopeName());
  246. //生成bean的名称
  247. String beanName = this.beanNameGenerator.generateBeanName(candidate, this.registry);
  248. //判断是不是抽象的beand定义
  249. if (candidate instanceof AbstractBeanDefinition) {
  250. postProcessBeanDefinition((AbstractBeanDefinition) candidate, beanName);
  251. }
  252. //注解的bean定义
  253. if (candidate instanceof AnnotatedBeanDefinition) {
  254. AnnotationConfigUtils.processCommonDefinitionAnnotations((AnnotatedBeanDefinition) candidate);
  255. }
  256. if (checkCandidate(beanName, candidate)) { //检查当前的和存主的bean定义是否有冲突
  257. //把候选的组件封装成BeanDefinitionHolder
  258. BeanDefinitionHolder definitionHolder = new BeanDefinitionHolder(candidate, beanName);
  259. definitionHolder =AnnotationConfigUtils.applyScopedProxyMode(scopeMetadata, definitionHolder, this.registry);
  260. //加入到bean定义的集合中
  261. beanDefinitions.add(definitionHolder);
  262. //注册当前的bean定义信息
  263. registerBeanDefinition(definitionHolder, this.registry);
  264. }
  265. }
  266. }
  267. return beanDefinitions;
  268. }
  269. org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider#findCandidateComponents
  270. 找到候选的组件 返回Set<BeanDefinition>的集合
  271. public Set<BeanDefinition> findCandidateComponents(String basePackage) {
  272. //候选的bean定义信息
  273. Set<BeanDefinition> candidates = new LinkedHashSet<BeanDefinition>();
  274. try {
  275. //拼接需要扫描包下面的类的路径 classpath*:com/tuling/testapplicationlistener/**/*.class
  276. String packageSearchPath = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX +
  277. resolveBasePackage(basePackage) + '/' + this.resourcePattern;
  278. //把路径解析成一个个.class文件
  279. Resource[] resources = this.resourcePatternResolver.getResources(packageSearchPath);
  280. boolean traceEnabled = logger.isTraceEnabled();
  281. boolean debugEnabled = logger.isDebugEnabled();
  282. //循环.class文件的resource对象
  283. for (Resource resource : resources) {
  284. if (traceEnabled) {
  285. logger.trace("Scanning " + resource);
  286. }
  287. //判断class文件是否可读
  288. if (resource.isReadable()) {
  289. try {
  290. //把resource对象 变为一个类的原信息读取器
  291. MetadataReader metadataReader = this.metadataReaderFactory.getMetadataReader(resource);
  292. //判断类的源信息读取器是否为候选的组件
  293. if (isCandidateComponent(metadataReader)) { //是候选的组件
  294. //把类元信息读取器封装成一个ScannedGenericBeanDefinition
  295. ScannedGenericBeanDefinition sbd = new ScannedGenericBeanDefinition(metadataReader);
  296. sbd.setResource(resource);
  297. sbd.setSource(resource);
  298. //是候选的组件
  299. if (isCandidateComponent(sbd)) {
  300. if (debugEnabled) {
  301. logger.debug("Identified candidate component class: " + resource);
  302. }
  303. //把当前解析出来的定义的加入到 BeanDefinition的集合中
  304. candidates.add(sbd);
  305. }
  306. else {
  307. if (debugEnabled) {
  308. logger.debug("Ignored because not a concrete top-level class: " + resource);
  309. }
  310. }
  311. }
  312. else {
  313. if (traceEnabled) {
  314. logger.trace("Ignored because not matching any filter: " + resource);
  315. }
  316. }
  317. }
  318. catch (Throwable ex) {
  319. throw new BeanDefinitionStoreException(
  320. "Failed to read candidate component class: " + resource, ex);
  321. }
  322. }
  323. else {
  324. if (traceEnabled) {
  325. logger.trace("Ignored because not readable: " + resource);
  326. }
  327. }
  328. }
  329. }
  330. catch (IOException ex) {
  331. throw new BeanDefinitionStoreException("I/O failure during classpath scanning", ex);
  332. }
  333. return candidates;
  334. }
  335. 是不是需要扫描的组件
  336. org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider#isCandidateComponent
  337. protected boolean isCandidateComponent(MetadataReader metadataReader) throws IOException {
  338. //是不是被排除的
  339. for (TypeFilter tf : this.excludeFilters) {
  340. if (tf.match(metadataReader, this.metadataReaderFactory)) {
  341. return false;
  342. }
  343. }
  344. //在被包含的组件
  345. for (TypeFilter tf : this.includeFilters) {
  346. if (tf.match(metadataReader, this.metadataReaderFactory)) {
  347. return isConditionMatch(metadataReader);
  348. }
  349. }
  350. return false;
  351. }
  352. 是否能够进行@Conditional判断
  353. org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider#isConditionMatch
  354. private boolean isConditionMatch(MetadataReader metadataReader) {
  355. if (this.conditionEvaluator == null) {
  356. this.conditionEvaluator = new ConditionEvaluator(getRegistry(), getEnvironment(), getResourceLoader());
  357. }
  358. return !this.conditionEvaluator.shouldSkip(metadataReader.getAnnotationMetadata());
  359. }