【Spring源碼解析】BeanFactoryPostProcessor【相關類】源碼解析

1 BeanFactoryPostProcessor作用

public interface BeanDefinitionRegistryPostProcessor extends BeanFactoryPostProcessor {
   /**
    * 可以修改容器Bean內部的定義信息,全部的bean definitions會加載但是bean沒有被實例化
    */
   void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException;
}

1.1 代碼

(1) Student

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Student {

    private String name;

}

(2) 配置文件

@ComponentScan("com.spring")
@Configuration
public class SpringConfig {
    @Primary
    @Bean
    public Student zhangsan(){
        return new Student("張三");
    }
    @Bean
    public Student lisi(){
        return new Student("李四");
    }
}

(3) 主程序

public class SpringApplicationContext {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class);
        Student bean = context.getBean(Student.class);
        System.out.println(bean.getName());
    }
}

在這裏插入圖片描述

1.2 添加配置文件

@Configuration
public class ZrsBeanFactoryPostProcessor implements BeanFactoryPostProcessor {
    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
        System.out.println("###############postProcessBeanFactory#################");
        System.out.println("bean 的數量爲:"+beanFactory.getBeanDefinitionCount());
        String[] beanDefinitionNames = beanFactory.getBeanDefinitionNames();
        System.out.println("BeanName爲:"+ Arrays.asList(beanDefinitionNames));
        //把李四設置成Primary
        BeanDefinition lisi = beanFactory.getBeanDefinition("lisi");
        lisi.setPrimary(true);
        //把張三設置成非Primary
        BeanDefinition zhangsan = beanFactory.getBeanDefinition("zhangsan");
        zhangsan.setPrimary(false);
    }
}

運行主程序:
在這裏插入圖片描述

2 BeanDefinitionRegistryPostProcessor

2.1 類圖

在這裏插入圖片描述

2.2 源代碼

public interface BeanDefinitionRegistryPostProcessor extends BeanFactoryPostProcessor {
   /**
    * BeanDefinitionRegistryPostProcessor擴充了BeanFactoryPostProcessor功能
    * BeanDefinitionRegistry可以給工廠中註冊Bean
    */
   void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException;
}

2.3 代碼

(1) 配置文件

@ComponentScan("com.spring")
@Configuration
public class SpringConfig {

}

(2) pojo

@Data
public class HelloWorld {

}

(3) ZrsBeanDefinitionRegistryPostProcessor

@Configuration
public class ZrsBeanDefinitionRegistryPostProcessor implements BeanDefinitionRegistryPostProcessor {
    @Override
    public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
        System.out.println("postProcessBeanDefinitionRegistry:");
        System.out.println("bean 的數量爲:"+registry.getBeanDefinitionCount());
        RootBeanDefinition rootBeanDefinition=new RootBeanDefinition(HelloWorld.class);
        registry.registerBeanDefinition("helloworld", rootBeanDefinition);
    }
    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
        System.out.println("postProcessBeanFactory:");
        System.out.println("bean 的數量爲:"+beanFactory.getBeanDefinitionCount());
    }
}

(4) 主程序

public class SpringApplicationContext {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class);
        HelloWorld bean = context.getBean(HelloWorld.class);
        System.out.println(bean);
    }
}

(5) 結果
分析:BeanDefinitionRegistryPostProcessor加強BeanFactoryPostProcessor,並且先運行postProcessBeanDefinitionRegistry,在運行postProcessBeanFactory。
在這裏插入圖片描述

4 源碼調試

在這裏插入圖片描述
(1) 分析方法棧
在這裏插入圖片描述
(2) IOC初始化調用位置 AbstractApplicationContext.,refresh方法
在這裏插入圖片描述(3) PostProcessorRegistrationDelegate invokeBeanFactoryPostProcessors 源碼分析

public static void invokeBeanFactoryPostProcessors(
      ConfigurableListableBeanFactory beanFactory, List<BeanFactoryPostProcessor> beanFactoryPostProcessors) {
 
   Set<String> processedBeans = new HashSet<>();
   if (beanFactory instanceof BeanDefinitionRegistry) {
      BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
      //1 存儲BeanFactoryPostProcessor,BeanDefinitionRegistryPostProcessor的處理器
      List<BeanFactoryPostProcessor> regularPostProcessors = new LinkedList<>();
      List<BeanDefinitionRegistryPostProcessor> registryProcessors = new LinkedList<>();
      //2 遍歷beanFactoryPostProcessors把BeanFactoryPostProcessor、BeanDefinitionRegistryPostProcessor分開
      for (BeanFactoryPostProcessor postProcessor : beanFactoryPostProcessors) {
         if (postProcessor instanceof BeanDefinitionRegistryPostProcessor) {
            BeanDefinitionRegistryPostProcessor registryProcessor =
                  (BeanDefinitionRegistryPostProcessor) postProcessor;
            //2.1 執行postProcessBeanDefinitionRegistry,並且添加BeanDefinitionRegistryPostProcessor
            registryProcessor.postProcessBeanDefinitionRegistry(registry);
            registryProcessors.add(registryProcessor);
         }
         else {
            //2.2 添加BeanFactoryPostProcessor
            regularPostProcessors.add(postProcessor);
         }
      }
      // Do not initialize FactoryBeans here: We need to leave all regular beans
      // uninitialized to let the bean factory post-processors apply to them!
      // Separate between BeanDefinitionRegistryPostProcessors that implement
      // PriorityOrdered, Ordered, and the rest.
      //3 當前的currentRegistryProcessors  
      List<BeanDefinitionRegistryPostProcessor> currentRegistryProcessors = new ArrayList<>();
      // First, invoke the BeanDefinitionRegistryPostProcessors that implement PriorityOrdered.
      //4 獲取BeanDefinitionRegistryPostProcessor.class   
      String[] postProcessorNames =
            beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
      //5 找出實現PriorityOrdered接口的BeanDefinitionRegistryPostProcessor  
      for (String ppName : postProcessorNames) {
         if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
            currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
            processedBeans.add(ppName);
         }
      }
      //6 排序,添加,並且運行當前所有currentRegistryProcessors的postProcessBeanDefinitionRegistry方法,清空currentRegistryProcessors
      sortPostProcessors(currentRegistryProcessors, beanFactory);
      registryProcessors.addAll(currentRegistryProcessors);
      invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
      currentRegistryProcessors.clear();
      // Next, invoke the BeanDefinitionRegistryPostProcessors that implement Ordered.
      //7 重新獲取,防止上文postProcessBeanDefinitionRegistry的方法添加了新的BeanDefinitionRegistryPostProcessor
      postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
      //8 分類,獲取實現Ordered的接口的BeanDefinitionRegistryPostProcessor
      for (String ppName : postProcessorNames) {
         if (!processedBeans.contains(ppName) && beanFactory.isTypeMatch(ppName, Ordered.class)) {
            currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
            processedBeans.add(ppName);
         }
      }
      //9 添加,註冊,調取當前BeanDefinitionRegistryPostProcessor所有的postProcessBeanDefinitionRegistry方法,清空currentRegistryProcessors  
      sortPostProcessors(currentRegistryProcessors, beanFactory);
      registryProcessors.addAll(currentRegistryProcessors);
      invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
      currentRegistryProcessors.clear();
      // Finally, invoke all other BeanDefinitionRegistryPostProcessors until no further ones appear.
      //10 處理沒有實現Ordered, PriorityOrdered接口的BeanDefinitionRegistryPostProcessor   
      boolean reiterate = true;
      while (reiterate) {
         reiterate = false;
         //循環獲取,防止BeanDefinitionRegistryPostProcessor添加新的BeanDefinitionRegistryPostProcessor對象    
         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.
      //11 調用所有BeanDefinitionRegistryPostProcessor的postProcessBeanFactory方法和BeanFactoryPostProcessor的postProcessBeanFactory方法
      invokeBeanFactoryPostProcessors(registryProcessors, beanFactory);
      invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory);
   }
   else {
      // Invoke factory processors registered with the context instance.
      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!
   //12 獲取BeanFactoryPostProcessor.class類型beannames 
   String[] postProcessorNames =
         beanFactory.getBeanNamesForType(BeanFactoryPostProcessor.class, true, false);
   // Separate between BeanFactoryPostProcessors that implement PriorityOrdered,
   // Ordered, and the rest.
   //13 存儲PriorityOrdered.class、Ordered、雙非的類名
   List<BeanFactoryPostProcessor> priorityOrderedPostProcessors = new ArrayList<>();
   List<String> orderedPostProcessorNames = new ArrayList<>();
   List<String> nonOrderedPostProcessorNames = new ArrayList<>();
   //14 分類
   for (String ppName : postProcessorNames) {
      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);
      }
   }
   // First, invoke the BeanFactoryPostProcessors that implement PriorityOrdered.
   //15 排序,調用BeanFactoryPostProcessor的postProcessBeanFactory類
   sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
   invokeBeanFactoryPostProcessors(priorityOrderedPostProcessors, beanFactory);
   // Next, invoke the BeanFactoryPostProcessors that implement Ordered.
   //16 存儲,排序,調用BeanFactoryPostProcessor實現了Order的postProcessBeanFactory類
   List<BeanFactoryPostProcessor> orderedPostProcessors = new ArrayList<>();
   for (String postProcessorName : orderedPostProcessorNames) {
      orderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
   }
   sortPostProcessors(orderedPostProcessors, beanFactory);
   invokeBeanFactoryPostProcessors(orderedPostProcessors, beanFactory);
   // Finally, invoke all other BeanFactoryPostProcessors.
   //17 最後調用雙非的BeanFactoryPostProcessor的postProcessBeanFactory方法
   List<BeanFactoryPostProcessor> nonOrderedPostProcessors = new ArrayList<>();
   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();
}

5 ConfigurationClassPostProcessor

作用:註冊Bean的信息,但不是實例化Bean
在這裏插入圖片描述

5.1 引入時機

(1) AnnotationConfigApplicationContext 構造
在這裏插入圖片描述
(2) AnnotationConfigApplicationContext() 構造
在這裏插入圖片描述
(3)AnnotatedBeanDefinitionReader 構造
在這裏插入圖片描述
(4) AnnotatedBeanDefinitionReader 構造
在這裏插入圖片描述
(5) AnnotationConfigUtils registerAnnotationConfigProcessors
在這裏插入圖片描述

(6) AnnotationConfigUtils registerAnnotationConfigProcessors
在這裏插入圖片描述

5.2 作用

(1) ConfigurationClassPostProcessor 實現了 PriorityOrdered 所以是最先調用

(2) 調試 PostProcessorRegistrationDelegate invokeBeanFactoryPostProcessors
在這裏插入圖片描述
(3) PostProcessorRegistrationDelegate invokeBeanDefinitionRegistryPostProcessors
在這裏插入圖片描述
(4) ConfigurationClassPostProcessor postProcessBeanDefinitionRegistry
在這裏插入圖片描述
(5) ConfigurationClassPostProcessor processConfigBeanDefinitions
在這裏插入圖片描述
(6) ConfigurationClassBeanDefinitionReader loadBeanDefinitions
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章