BeanFactoryPostProcessor 接口的 postProcessBeanFactory 方法的执行时机大体分为两类,第一类是 bean 继承了 BeanDefinitionRegistryPostProcessor 接口的,第二类是直接继承了 BeanFactoryPostProcessor 接口的

直接实现了 BeanDefinitionRegistryPostProcessor 接口

因为 BeanDefinitionRegistryPostProcessor 接口继承了 BeanFactoryPostProcessor 接口,所以它是 BeanFactoryPostProcessor 的子类

  1. public interface BeanDefinitionRegistryPostProcessor extends BeanFactoryPostProcessor {
  2. void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException;
  3. }

那么其 postProcessBeanFactory 方法的执行时机是在,完成了 postProcessBeanDefinitionRegistry 方法后,开始执行

直接实现了 BeanFactoryPostProcessor 接口

直接实现 BeanFactoryPostProcessor 接口的类,它的在执行时机晚于实现 BeanDefinitionRegistryPostProcessor 接口的类,不过它也有自己的一定执行策略

  1. 实现了 PriorityOrdered 接口
  2. 实现了 Ordered 接口
  3. 没有实现任何接口的
  1. List<BeanFactoryPostProcessor> priorityOrderedPostProcessors = new ArrayList<>();
  2. List<String> orderedPostProcessorNames = new ArrayList<>();
  3. List<String> nonOrderedPostProcessorNames = new ArrayList<>();
  4. for (String ppName : postProcessorNames) {
  5. if (processedBeans.contains(ppName)) {
  6. // 已经在第一阶段执行过了,此处就不执行了
  7. // skip - already processed in first phase above
  8. }
  9. else if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
  10. priorityOrderedPostProcessors.add(beanFactory.getBean(ppName, BeanFactoryPostProcessor.class));
  11. }
  12. else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
  13. orderedPostProcessorNames.add(ppName);
  14. }
  15. else {
  16. nonOrderedPostProcessorNames.add(ppName);
  17. }
  18. }
  19. // First, invoke the BeanFactoryPostProcessors that implement PriorityOrdered.
  20. sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
  21. invokeBeanFactoryPostProcessors(priorityOrderedPostProcessors, beanFactory);
  22. // Next, invoke the BeanFactoryPostProcessors that implement Ordered.
  23. List<BeanFactoryPostProcessor> orderedPostProcessors = new ArrayList<>();
  24. for (String postProcessorName : orderedPostProcessorNames) {
  25. orderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
  26. }
  27. sortPostProcessors(orderedPostProcessors, beanFactory);
  28. invokeBeanFactoryPostProcessors(orderedPostProcessors, beanFactory);
  29. // Finally, invoke all other BeanFactoryPostProcessors.
  30. List<BeanFactoryPostProcessor> nonOrderedPostProcessors = new ArrayList<>();
  31. for (String postProcessorName : nonOrderedPostProcessorNames) {
  32. nonOrderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
  33. }
  34. invokeBeanFactoryPostProcessors(nonOrderedPostProcessors, beanFactory);