这部分处理的是 IOC 容器启动过程 4-postProcessBeanFactory () 中注册的扩展。接下来的操作就和上面很类似了。

阶段1- 查找所有的 Bean 并分类

  1. String[] postProcessorNames =
  2. beanFactory.getBeanNamesForType(BeanFactoryPostProcessor.class, true, false);
  3. // Separate between BeanFactoryPostProcessors that implement PriorityOrdered,
  4. // Ordered, and the rest.
  5. List<BeanFactoryPostProcessor> priorityOrderedPostProcessors = new ArrayList<>();
  6. List<String> orderedPostProcessorNames = new ArrayList<>();
  7. List<String> nonOrderedPostProcessorNames = new ArrayList<>();
  8. for (String ppName : postProcessorNames) {
  9. if (processedBeans.contains(ppName)) {
  10. // skip - already processed in first phase above
  11. } else if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
  12. priorityOrderedPostProcessors.add(beanFactory.getBean(ppName
  13. , BeanFactoryPostProcessor.class));
  14. } else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
  15. orderedPostProcessorNames.add(ppName);
  16. } else {
  17. nonOrderedPostProcessorNames.add(ppName);
  18. }
  19. }

阶段2- 顺序执行有 PriorityOrdered的BeanFactoryPostProcessor

  1. // First, invoke the BeanFactoryPostProcessors that implement PriorityOrdered.
  2. sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
  3. invokeBeanFactoryPostProcessors(priorityOrderedPostProcessors, beanFactory);

阶段3- 顺序执行有 Ordered的BeanFactoryPostProcessor

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

阶段4- 顺序其他 BeanFactoryPostProcessor

  1. List<BeanFactoryPostProcessor> nonOrderedPostProcessors
  2. = new ArrayList<>(nonOrderedPostProcessorNames.size());
  3. for (String postProcessorName : nonOrderedPostProcessorNames) {
  4. nonOrderedPostProcessors.add(beanFactory.getBean(postProcessorName
  5. , BeanFactoryPostProcessor.class));
  6. }
  7. invokeBeanFactoryPostProcessors(nonOrderedPostProcessors, beanFactory);

最终清除缓存

  1. beanFactory.clearMetadataCache();