SpringBoot源码第四章-invokeBeanFactoryPostProcessors

invokeBeanFactoryPostProcessors()

实例化并调用所有已经注册的bean 工厂后置处理器(BeanFactoryPostProcessor)

protected void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory) {
	PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(beanFactory, getBeanFactoryPostProcessors());

	// Detect a LoadTimeWeaver and prepare for weaving, if found in the meantime
	// (e.g. through an @Bean method registered by ConfigurationClassPostProcessor)
	if (beanFactory.getTempClassLoader() == null && beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
		beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
		beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
	}
}

调用PostProcessorRegistrationDelegate的invokeBeanFactoryPostProcessors方法

public static void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory, List<BeanFactoryPostProcessor> beanFactoryPostProcessors) {

	// 保存所有调用过的PostProcessor的beanName
	Set<String> processedBeans = new HashSet<>();

	if (beanFactory instanceof BeanDefinitionRegistry) {
		BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
         //这俩个list主要用来收集BeanFactoryPostProcessor和BeanDefinitionRegistryPostProcessor
		List<BeanFactoryPostProcessor> regularPostProcessors = new ArrayList<>();
		List<BeanDefinitionRegistryPostProcessor> registryProcessors = new ArrayList<>();

		for (BeanFactoryPostProcessor postProcessor : beanFactoryPostProcessors) {
            //对已经注册在DefaultListBeanFactory的beanFactoryPostProcessors进行分类
		   if (postProcessor instanceof BeanDefinitionRegistryPostProcessor) {
		      BeanDefinitionRegistryPostProcessor registryProcessor = (BeanDefinitionRegistryPostProcessor) postProcessor;
            /** 已注册在DefaultListBeanFactory的BeanDefinitionRegistryPostProcessor优先级最高
              * 如果postProcessor是BeanDefinitionRegistryPostProcessor的实例
              * 执行postProcessor的postProcessBeanDefinitionRegistry
              * 为什么执行完之后还要保存到List中呢?
              * 因为这里只是执行完了BeanDefinitionRegistryPostProcessor的回调
              * 父类BeanFactoryPostProcessor的方法还没有进行回调
              */ 
		      registryProcessor.postProcessBeanDefinitionRegistry(registry);
		      registryProcessors.add(registryProcessor);
		  }else {
              // 则是BeanFactoryPostProcessor的实例,存放在List中,后面会进行回调
		      regularPostProcessors.add(postProcessor);
		  }
		}

		// 定义了一个集合来存放当前需要执行的BeanDefinitionRegistryPostProcessor
		List<BeanDefinitionRegistryPostProcessor> currentRegistryProcessors = new ArrayList<>();

		// First, invoke the BeanDefinitionRegistryPostProcessors that implement PriorityOrdered.

      /** 首先执行实现了PriorityOrdered的BeanDefinitionRegistryPostProcessor
        * 这里只能获取到Spring内部注册的BeanDefinitionRegistryPostProcessor,因为到这里spring还没有去扫描Bean,获取不到
        * 我们通过@Component标志的自定义的BeanDefinitionRegistryPostProcessor
        * 一般默认情况下,这里只有一个beanName,
        * org.springframework.context.annotation.internalConfigurationAnnotationProcessor
        * 对应的BeanClass:ConfigurationClassPostProcessor
        */
		String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
		for (String ppName : postProcessorNames) {
		  if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
			currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
             //保存调用过的beanName
			processedBeans.add(ppName);
		      }
		  }
          //排序
		  sortPostProcessors(currentRegistryProcessors, beanFactory);
          //registryProcessors存放的是BeanDefinitionRegistryPostProcessor
		  registryProcessors.addAll(currentRegistryProcessors);

           // 执行BeanDefinitionRegistryPostProcessor,一般默认情况下,只有ConfigurationClassPostProcessor
          // ConfigurationClassPostProcessor的具体作用后面再讲,这里先认为它执行完扫描,并且注册BeanDefinition
		  invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
		  // 清空临时变量,后面再使用
          currentRegistryProcessors.clear();

		  // 第二步执行实现了Ordered的BeanDefinitionRegistryPostProcessor
         // 这里为什么要再一次从beanFactory中获取所有的BeanDefinitionRegistryPostProcessor,是因为上面的操作有可能注册了
        // 新的BeanDefinitionRegistryPostProcessor,所以再获取一次
		  postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
		  for (String ppName : postProcessorNames) {
		        if (!processedBeans.contains(ppName) && beanFactory.isTypeMatch(ppName, Ordered.class)) {
				currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
				processedBeans.add(ppName);
			  }
			}
		  sortPostProcessors(currentRegistryProcessors, beanFactory);
		  registryProcessors.addAll(currentRegistryProcessors);
		  invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
		  currentRegistryProcessors.clear();

		  /** 上面两步的套路是一模一样的,唯一不一样的地方是第一步执行的是实现了PriorityOrdered的
            * BeanDefinitionRegistryPostProcessor,第二步是执行的是实现了Ordered的
             * BeanDefinitionRegistryPostProcessor
          * 最后一步,执行没有实现PriorityOrdered或者Ordered的BeanDefinitionRegistryPostProcessor
            *  比较不一样的是,这里有个while循环,是因为在实现BeanDefinitionRegistryPostProcessor的方法的过程中有可能
            *  会注册新的BeanDefinitionRegistryPostProcessor,所以需要处理,直到不会出现新BeanDefinitionRegistryPostProcessor为止
            */
		  boolean reiterate = true;
		  while (reiterate) {
			reiterate = false;
			postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
			for (String ppName : postProcessorNames) {
				if (!processedBeans.contains(ppName)) {
                    /**
                      *  发现还有未处理过的BeanDefinitionRegistryPostProcessor,按照套路放进list中
                      *  reiterate标记为true,后面还要再执行一次这个循环,因为执行新的BeanDefinitionRegistryPostProcessor有可能会
                      *  注册新的BeanDefinitionRegistryPostProcessor
                      */
					currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
					processedBeans.add(ppName);
					reiterate = true;
				}
			}
			sortPostProcessors(currentRegistryProcessors, beanFactory);
			registryProcessors.addAll(currentRegistryProcessors);
			invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
			currentRegistryProcessors.clear();
		  }

		 //方法开头前几行分类的两个list就是在这里调用
         // BeanDefinitionRegistryPostProcessor extends BeanFactoryPostProcessor
         // 刚刚执行了BeanDefinitionRegistryPostProcessor的方法
         // 现在要执行父类BeanFactoryPostProcessor的方法
		  invokeBeanFactoryPostProcessors(registryProcessors, beanFactory);
		  invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory);
		} else {
		  // Invoke factory processors registered with the context instance.
		  invokeBeanFactoryPostProcessors(beanFactoryPostProcessors, beanFactory);
		}

		// 上面BeanFactoryPostProcessor的回调可能又注册了一些类,下面需要再走一遍之前的逻辑
		String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanFactoryPostProcessor.class, true, false);

		/** Separate between BeanFactoryPostProcessors that implement PriorityOrdered,
		  *  根据不同的优先级,分成三类
          */
		List<BeanFactoryPostProcessor> priorityOrderedPostProcessors = new ArrayList<>();
		List<String> orderedPostProcessorNames = new ArrayList<>();
		List<String> nonOrderedPostProcessorNames = new ArrayList<>();
		for (String ppName : postProcessorNames) {
             // 上面处理BeanDefinitionRegistryPostProcessor的时候已经处理过,这里不再重复处理
            // 因为BeanDefinitionRegistryPostProcessor extends BeanFactoryPostProcessor
			if (processedBeans.contains(ppName)) {
			// skip - already processed in first phase above
			}  else if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
			    priorityOrderedPostProcessors.add(beanFactory.getBean(ppName, BeanFactoryPostProcessor.class));
			}  else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
			    orderedPostProcessorNames.add(ppName);
			}  else {
			    nonOrderedPostProcessorNames.add(ppName);
			}
		}

        /**  
         *下面的逻辑跟上面是一致的,先处理实现了PriorityOrdered接口的
         *   再处理实现了Ordered接口的
         *   最后处理普通的BeanFactoryPostProcessor
         */
		sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
		invokeBeanFactoryPostProcessors(priorityOrderedPostProcessors, beanFactory);

		// Next, invoke the BeanFactoryPostProcessors that implement Ordered.
		List<BeanFactoryPostProcessor> orderedPostProcessors = new ArrayList<>(orderedPostProcessorNames.size());
		for (String postProcessorName : orderedPostProcessorNames) {
			orderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
		}
		sortPostProcessors(orderedPostProcessors, beanFactory);
		invokeBeanFactoryPostProcessors(orderedPostProcessors, beanFactory);

		// Finally, invoke all other BeanFactoryPostProcessors.
		List<BeanFactoryPostProcessor> nonOrderedPostProcessors = new ArrayList<>(nonOrderedPostProcessorNames.size());
		for (String postProcessorName : nonOrderedPostProcessorNames) {
			nonOrderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
		}
		invokeBeanFactoryPostProcessors(nonOrderedPostProcessors, beanFactory);

		// Clear cached merged bean definitions since the post-processors might have
		// 因为各种BeanFactoryPostProcessor可能修改了BeanDefinition
       // 所以这里需要清除缓存,需要的时候再通过merge的方式获取
		beanFactory.clearMetadataCache();
	}
posted @   浪成于微澜之间  阅读(61)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)
点击右上角即可分享
微信分享提示