“This is the 8th day of my participation in the Gwen Challenge in November. Check out the details: The Last Gwen Challenge in 2021”

1. Introduction

This article is a continuation of the Spring IOC container initialization principle analysis (Section 1). If you have any doubts, please read the previous article first, or ask me to discuss.

Refresh (); refresh()

If you need to copy the code, go to the Spring IOC container initialization principle analysis (Section 1).

3. Method 2.4 postProcessBeanFactory

This method is officially defined as modifying its internal bean factory after the standard initialization of the application context. All bean definitions will be loaded, but the bean has not yet been instantiated. This allows you to register special BeanPostProcessors, etc., in a particular ApplicationContext implementation

It in the org. Springframework. Context. Support. AbstractApplicationContext the default is an empty implementation, the source code is as follows

This class is mainly spring official to our custom extensions, can realize the function of some custom, we won’t the custom here, look at the web project usually is (AbstractRefreshableWebApplicationContext) default implementation

protected void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
    / / add ServletContextAwareProcessor post processor
    / / implementation ServletContextAwareProcessor can obtain servletContext
    beanFactory.addBeanPostProcessor(new ServletContextAwareProcessor(this.servletContext, this.servletConfig));
    // Ignore auto injection. For auto assembly, ignore the given dependency interface.
    beanFactory.ignoreDependencyInterface(ServletContextAware.class);
    beanFactory.ignoreDependencyInterface(ServletConfigAware.class);
    / / web registration
    WebApplicationContextUtils.registerWebApplicationScopes(beanFactory, this.servletContext);
    // Register context-specific beans
    WebApplicationContextUtils.registerEnvironmentBeans(beanFactory, this.servletContext, this.servletConfig);
}
Copy the code

4. The method (2.5 invokeBeanFactoryPostProcessors) explanation

The main functions of this method are: Spring BeanFactoryPostProcessor instantiate and call all registered, in the order specified (i.e. BeanDefinitionRegistryPostProcessor is a subclass of spring BeanFactoryPostProcessor, when executed, Is executed before BeanFactoryPostProcessor.)

The BeanFactoryPostProcessor interface is the extension point exposed when Spring initializes the BeanFactory. The Spring IoC container allows the BeanFactoryPostProcessor to be used before instantiating singleton beans. Read its configuration information and can modify it.

Source code is as follows:

  • It is the core method of PostProcessorRegistrationDelegate. InvokeBeanFactoryPostProcessors (the beanFactory, GetBeanFactoryPostProcessors ()), before him Let’s talk about getBeanFactoryPostProcessors ()
  • The following if block: Determine if the current the beanFactory temporary class loader is null and the beanFactory contain loadTimeWeaver this bean will give it to add a LoadTimeWeaverAwareProcessor processor, set the default temporary class loader
  1. First of all tell me the first getBeanFactoryPostProcessors () method

This method gets a custom beanFactoryPostProcessor. What is custom? Neither by scanning to obtain annotations (such as the @autowired) form, but by manually context. AddBeanFactoryPostProcessor (spring beanFactoryPostProcessor) to complete the custom, the list is null by default

  1. Then we could to emphatically analyze the PostProcessorRegistrationDelegate. InvokeBeanFactoryPostProcessors (the beanFactory, This method getBeanFactoryPostProcessors ())

The current default is the beanFactory DefaultListableBeanFactory as to why is this, a speak as I’ve said, here have a look at its inheritance diagram, convenient source code analysis we use below. Figure 1 is as follows:

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

   Set<String> processedBeans = new HashSet<>();

   //判断是否含有BeanDefinitionRegistry这个类型的,如过是则进入,默认情况下是DefaultListableBeanFactory 
   //如图一可知,它实现了BeanDefinitionRegistry
   if (beanFactory instanceof BeanDefinitionRegistry) {
       //转成BeanDefinitionRegistry类型
      BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
      // 记录通过硬编码方式注册的BeanFactoryPostProcessor 类型的处理器
      List<BeanFactoryPostProcessor> regularPostProcessors = new ArrayList<>();
      // 记录通过硬编码方式注册的BeanDefinitionRegistryPostProcessor  类型的处理器
      List<BeanDefinitionRegistryPostProcessor> registryProcessors = new ArrayList<>();

      //遍历beanFactoryPostProcessors 
      for (BeanFactoryPostProcessor postProcessor : beanFactoryPostProcessors) {
          //判断是否属于BeanDefinitionRegistryPostProcessor
         if (postProcessor instanceof BeanDefinitionRegistryPostProcessor) {
            BeanDefinitionRegistryPostProcessor registryProcessor =
                  (BeanDefinitionRegistryPostProcessor) postProcessor;
               // 在应用程序上下文的标准初始化之后修改其内部bean定义注册表。将加载所有常规bean定义,但还没有实例化bean。
               //仅对 BeanDefinitionRegistry 子类的BeanFactory 起作用
            registryProcessor.postProcessBeanDefinitionRegistry(registry);
            registryProcessors.add(registryProcessor);
         }
         else {
            regularPostProcessors.add(postProcessor);
         }
      }

      // Do not initialize FactoryBeans here: We need to leave all regular beans
      //不要在这里初始化FactoryBeans:我们需要保留所有常规Bean
      // uninitialized to let the bean factory post-processors apply to them!
      //未初始化以让bean工厂后处理器应用于它们
      // Separate between BeanDefinitionRegistryPostProcessors that implement
      // PriorityOrdered, Ordered, and the rest.
      // 记录通过配置方式注册的 BeanDefinitionRegistryPostProcessor  类型的处理器
      List<BeanDefinitionRegistryPostProcessor> currentRegistryProcessors = new ArrayList<>();

        // 首先,调用实现PriorityOrdered的BeanDefinitionRegistryPostProcessor。
      // First, invoke the BeanDefinitionRegistryPostProcessors that implement PriorityOrdered.
      
      //获取所有 属于BeanDefinitionRegistryPostProcessor该类型的 beanName
      String[] postProcessorNames =
            beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
      for (String ppName : postProcessorNames) {
      //判断它是否实现了PriorityOrdered
         if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
             // 记录到currentRegistryProcessors中
            currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
            processedBeans.add(ppName);
         }
      }
      // 对currentRegistryProcessors里面的元素进行排序
      sortPostProcessors(currentRegistryProcessors, beanFactory);
      registryProcessors.addAll(currentRegistryProcessors);
     
    //registryProcessors中保存了所有执行过 postProcessBeanDefinitionRegistry方法的bean,
    //现在再来执行这些currentRegistryProcessors 中所有bean 的 postProcessBeanDefinitionRegistry 方法
      invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
      //清空 currentRegistryProcessors
      currentRegistryProcessors.clear();

        
      // Next, invoke the BeanDefinitionRegistryPostProcessors that implement Ordered.
      
      //这个和上面的一样只不过把 PriorityOrdered.class换成了Ordered.class这样就保证了 他们的执行顺序 PriorityOrdered, Ordered, and the rest.(ps:最先执行的是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();

      // Finally, invoke all other BeanDefinitionRegistryPostProcessors until no further ones appear.
      //最后,调用所有其他的BeanDefinitionRegistryPostProcessors,直到没有调用为止
      
      boolean reiterate = true;
      while (reiterate) {
         reiterate = false;
         //这里获取所有没有实现排序的 BeanDefinitionRegistryPostProcessor 调用它们的 postProcessBeanDefinitionRegistry 方法 进行激活
         postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
         for (String ppName : postProcessorNames) {
            if (!processedBeans.contains(ppName)) {
               currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
               processedBeans.add(ppName);
               reiterate = true;
            }
         }
         sortPostProcessors(currentRegistryProcessors, beanFactory);
         registryProcessors.addAll(currentRegistryProcessors);
         invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
         currentRegistryProcessors.clear();
      }

      // Now, invoke the postProcessBeanFactory callback of all processors handled so far.
      
        // 到这里,所有的 BeanDefinitionRegistryPostProcessor 的postProcessBeanDefinitionRegistry 都已经激活结束,开始激活 postProcessBeanFactory 方法
      invokeBeanFactoryPostProcessors(registryProcessors, beanFactory);
      // registryProcessors 记录的是硬编码注入的BeanDefinitionRegistryPostProcessor,这里激活的是 postProcessBeanFactory 方法
      invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory);
      // 至此处理完beanFactory是这种类型BeanDefinitionRegistry
   }

   else {
      // Invoke factory processors registered with the context instance.
      //调用注册到上下文实例的工厂处理程序。
      //当 beanFactory instanceof BeanDefinitionRegistry = false,即
     BeanDefinitionRegistryPostProcessor.的postProcessBeanDefinitionRegistry 并不生效,就直接激活postProcessBeanFactory方法即可。
      invokeBeanFactoryPostProcessors(beanFactoryPostProcessors, beanFactory);
   }

   // Do not initialize FactoryBeans here: We need to leave all regular beans
   // uninitialized to let the bean factory post-processors apply to them!
   
   //获取所有的后置处理器的beanName
   String[] postProcessorNames =
         beanFactory.getBeanNamesForType(BeanFactoryPostProcessor.class, true, false);

   // Separate between BeanFactoryPostProcessors that implement PriorityOrdered,
   // Ordered, and the rest.
   
   //创建不同的排序集合,按照PriorityOrdered、Ordered、默认 这样的顺序调用
   List<BeanFactoryPostProcessor> priorityOrderedPostProcessors = new ArrayList<>();
   List<String> orderedPostProcessorNames = new ArrayList<>();
   List<String> nonOrderedPostProcessorNames = new ArrayList<>();
   for (String ppName : postProcessorNames) {
      if (processedBeans.contains(ppName)) {
         // skip - already processed in first phase above
         // 如果processedBeans包含这个ppName,说明已经处理过了  此处跳过即可
      }
      // 否则判断它们实现的排序类型,分别加到对应的list中去
      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);
      }
   }

   // First, invoke the BeanFactoryPostProcessors that implement PriorityOrdered.
   
   // 这里是先排序,然后先执行实现了PriorityOrdered的BeanFactoryPostProcess
   sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
   invokeBeanFactoryPostProcessors(priorityOrderedPostProcessors, beanFactory);

   // Next, invoke the BeanFactoryPostProcessors that implement Ordered.
   
   //处理实现了 Ordered接口的BeanFactoryPostProcess
   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
   // modified the original metadata, e.g. replacing placeholders in values...
   
   // 清除缓存
   beanFactory.clearMetadataCache();
}
Copy the code

5 subtotal

  1. BeanDefinitionRegistryPostProcessor and spring BeanFactoryPostProcessor difference:
  • They are part of Spring’s post-processor and can be implemented to dynamically register bean definitions, dynamically modify bean definitions, and dynamically modify beans.

  • The BeanDefinitionRegistryPostProcessor postProcessBeanDefinitionRegistry Method in view of the ConfigurableListableBeanFactory is BeanDefinitionRegistry type, can realize to BeanDefinition add and delete operations such as, But for non ConfigurableListableBeanFactory type the BeanFactory, it doesn’t work.

  • BeanFactoryPostProcessor. PostProcessBeanFactory is for all BeanFactories.

  • PostProcessBeanDefinitionRegistry call time before postProcessBeanFactory.

  1. Psychological smaller

At the beginning, this method was quite long, which surprised me a lot. After that, I took some time to work on it bit by bit, and finally I got a general understanding of it. If there is something wrong, please point it out. The next article will explain emphatically 2.6 registerBeanPostProcessors (ConfigurableListableBeanFactory the beanFactory) method