Spring5源码解析4-refresh方法之invokeBeanFactoryPostProcessors
invokeBeanFactoryPostProcessors(beanFactory);方法源码如下:
protected void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory) {
// getBeanFactoryPostProcessors 获取的是 this.beanFactoryPostProcessors;
//this.beanFactoryPostProcessors 只能通过 AbstractApplicationContext.addBeanFactoryPostProcessor 方法添加
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()));
}
}
getBeanFactoryPostProcessors()方法获取的是AbstractApplicationContext#beanFactoryPostProcessors这个成员变量。
这个成员变量只能通过代码中手动编码调用AbstractApplicationContext#addBeanFactoryPostProcessor方法来添加新的元素。很明显,我们这里为空。
invokeBeanFactoryPostProcessors(beanFactory)方法的主要的逻辑在PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors方法中:
//PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(beanFactory, getBeanFactoryPostProcessors())源码
public static void invokeBeanFactoryPostProcessors(
ConfigurableListableBeanFactory beanFactory, List<BeanFactoryPostProcessor> beanFactoryPostProcessors) {
// Invoke BeanDefinitionRegistryPostProcessors first, if any.
Set<String> processedBeans = new HashSet<>();
if (beanFactory instanceof BeanDefinitionRegistry) {
BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
List<BeanFactoryPostProcessor> regularPostProcessors = new ArrayList<>();
List<BeanDefinitionRegistryPostProcessor> registryProcessors = new ArrayList<>();
//beanFactoryPostProcessors是传进来里的对象,把传入的对象分类放入 BeanFactoryPostProcessor 和 BeanDefinitionRegistryPostProcessor
//BeanDefinitionRegistryPostProcessor extends BeanFactoryPostProcessor ,是一个特殊的 BeanFactoryPostProcessor
for (BeanFactoryPostProcessor postProcessor : beanFactoryPostProcessors) {
if (postProcessor instanceof BeanDefinitionRegistryPostProcessor) {
BeanDefinitionRegistryPostProcessor registryProcessor =
(BeanDefinitionRegistryPostProcessor) postProcessor;
//如果传入的beanFactoryPostProcessors是它的子类,即:BeanDefinitionRegistryPostProcessor
//则执行传入的BeanDefinitionRegistryPostProcessor的postProcessBeanDefinitionRegistry方法
registryProcessor.postProcessBeanDefinitionRegistry(registry);
registryProcessors.add(registryProcessor);
} else {
regularPostProcessors.add(postProcessor);
}
}
// Do noitialize 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.
List<BeanDefinitionRegistryPostProcessor> currentRegistryProcessors = new ArrayList<>();
// First, invoke the BeanDefinitionRegistryPostProcessors that implement PriorityOrdered.
//这里只能拿到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)) {
//beanFactory.getBean, 这里开始创建BeanDefinitionRegistryPostProcessor bean 了
currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
processedBeans.add(ppName);
}
}
//排序
sortPostProcessors(currentRegistryProcessors, beanFactory);
// registryProcessors 中放的是 BeanDefinitionRegistryPostProcessor
// 因为这里只执行eanDefinitionRegistryPostProcessor中独有的方法,而不会执行其父类即BeanFactoryProcessor的方法
// 所以这里需要把处理器放入一个集合中,后续统一执行父类的方法
registryProcessors.addAll(currentRegistryProcessors);
// 执行BeanDefinitionRegistryPostProcessor,currentRegistryProcessors中放的是spring内部的BeanDefinitionRegistryPostProcessor
// 默认情况下,只有 org.springframework.context.annotation.ConfigurationClassPostProcessor
// ConfigurationClassPostProcessor 里面就是在执行扫描Bean,并且注册BeanDefinition
invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
// 清空这个临时变量,方便后面再使用
currentRegistryProcessors.clear();
// Next, invoke the BeanDefinitionRegistryPostProcessors that implement Ordered.
// 这里已经可以获取到我们通过注册到Spring容器的 BeanDefinitionRegistryPostProcessor 了
postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
for (String ppName : postProcessorNames) {
// 之前优先处理的是实现PriorityOrdered接口的,而PriorityOrdered接口也实现了Ordered接口
// 所有这里需要把之前已经处理过的给过滤掉
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);
// 执行BeanDefinitionRegistryPostProcessor
invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
//清空临时变量
currentRegistryProcessors.clear();
// Finally, invoke all other BeanDefinitionRegistryPostProcessors until no further ones appear.
boolean reiterate = true;
while (reiterate) {
reiterate = false;
postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
for (String ppName : postProcessorNames) {
//执行没有实现Ordered接口的BeanDefinitionRegistryPostProcessor
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.
// List<BeanDefinitionRegistryPostProcessor> registryProcessors
// 之前已经执行过BeanDefinitionRegistryPostProcessor独有方法,现在执行其父类方法
invokeBeanFactoryPostProcessors(registryProcessors, beanFactory);
// List<BeanFactoryPostProcessor> regularPostProcessors
// 执行 BeanFactoryPostProcessor 方法
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!
// 获取 BeanFactoryPostProcessor 的 beanName
String[] postProcessorNames =
beanFactory.getBeanNamesForType(BeanFactoryPostProcessor.class, true, false);
// Separate between BeanFactoryPostProcessors that implement PriorityOrdered,
// Ordered, and the rest.
List<BeanFactoryPostProcessor> priorityOrderedPostProcessors = new ArrayList<>();
List<String> orderedPostProcessorNames = new ArrayList<>();
List<String> nonOrderedPostProcessorNames = new ArrayList<>();
for (String ppName : postProcessorNames) {
// 如果已经被执行过了,就不在执行
// 因为一开始先获取的BeanDefinitionRegistryPostProcessor,而BeanDefinitionRegistryPostProcessor继承了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);
}
}
// First, invoke the BeanFactoryPostProcessors that implement PriorityOrdered.
// 根据不同的优先级,按序执行 BeanFactoryPostProcessor
sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
invokeBeanFactoryPostProcessors(priorityOrderedPostProcessors, beanFactory);
// Next, invoke the BeanFactoryPostProcessors that implement Ordered.
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.
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();
}
源码超级长,我们慢慢来看。
Spring容器使用的
BeanFactory是DefaultListableBeanFactory,它实现了BeanDefinitionRegistry接口,if条件成立。优先处理程序传进来的
beanFactoryPostProcessors,也就是我们手动调用AbstractApplicationContext#addBeanFactoryPostProcessor方法来添加的BeanFactoryPostProcessor。BeanFactoryPostProcessor是一个顶级接口,他还有一个子类BeanDefinitionRegistryPostProcessor。在该方法中声明了两个List来存放BeanFactoryPostProcessor和BeanDefinitionRegistryPostProcessor,以便控制这两个接口方法的执行。遍历传入的
List<BeanFactoryPostProcessor> beanFactoryPostProcessors,将其分类放到两个List中。如果传入的是BeanDefinitionRegistryPostProcessor类,则先执行BeanDefinitionRegistryPostProcessor类中独有的方法postProcessBeanDefinitionRegistry方法。当然,我们这里传入的List<BeanFactoryPostProcessor> beanFactoryPostProcessors为空。第一次执行
beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);方法,从容器中获取BeanDefinitionRegistryPostProcessor类型的Bean的name(这里只是获取名称,还没有实例化Bean)。注意,程序执行到这里,Spring还没有扫描包,还没有将项目中的Bean注册到容器中。默认情况下,这里返回的数据为如下图所示。回忆一下,这个BeanDefinition是在什么时候被加入到BeanFactory的呢?是在AnnotationConfigApplicationContext的无参构造器中创建reader时注册的BeanDefinition。其中BeanName为org.springframework.context.annotation.internalConfigurationAnnotationProcessor,对应的Class为org.springframework.context.annotation.ConfigurationClassPostProcessor。
遍历这个获取的
postProcessorNames,如果实现了PriorityOrdered接口,就调用beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class)方法,从容器中获取这个Bean,将其加入到临时变量List<BeanDefinitionRegistryPostProcessor> currentRegistryProcessors中。对
currentRegistryProcessors中的元素进行排序,然后执行BeanDefinitionRegistryPostProcessor中的特有方法postProcessBeanDefinitionRegistry。注意哦,这里没有执行其父类的方法,而是又将其放到List<BeanDefinitionRegistryPostProcessor> registryProcessors中,到后面再执行其父类方法。默认情况下,此时
currentRegistryProcessors中只有一个Bean即:org.springframework.context.annotation.ConfigurationClassPostProcessor(它实现了PriorityOrdered接口)。ConfigurationClassPostProcessor是一个非常重要的类,我们后面在讲。当程序执行完ConfigurationClassPostProcessor的BeanDefinitionRegistryPostProcessor方法后,我们程序中的Bean就被注册到了Spring容器中了,需要注意的是,这里还只是注册了BeanDefinition,还没有创建Bean对象。

当第二次执行
postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);方法,此时因为之前已经完成了Bean的扫描,所以如果我们有自定义的BeanDefinitionRegistryPostProcessor就可以在这里被获取了。获取之前,判断其是否实现Ordered接口,并且之前没有被执行过,则调用getBean方法,从容器中获取该Bean,然后进行排序,执行postProcessBeanDefinitionRegistry方法。前面已经按顺序执行了实现
PriorityOrdered和Ordered接口的BeanDefinitionRegistryPostProcessor,最后,执行没有实现Ordered接口的BeanDefinitionRegistryPostProcessor的postProcessBeanDefinitionRegistry方法。执行完之后再BeanDefinitionRegistryPostProcessor的父类方法postProcessBeanFactory。获取容器中还没有被执行过的实现
BeanFactoryPostProcessor接口的Bean,然后按顺序执行的postProcessBeanFactory。默认情况下,这里会获取到:

由于Bean org.springframework.context.annotation.internalConfigurationAnnotationProcessor(对应的Class为org.springframework.context.annotation.ConfigurationClassPostProcessor)在之前已经被执行了,这里只会执行Bean org.springframework.context.event.internalEventListenerProcessor(对应的Class为org.springframework.context.event.EventListenerMethodProcessor)的postProcessBeanFactory方法,源码如下:
//org.springframework.context.event.EventListenerMethodProcessor#postProcessBeanFactory 源码
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
this.beanFactory = beanFactory;
Map<String, EventListenerFactory> beans = beanFactory.getBeansOfType(EventListenerFactory.class, false, false);
List<EventListenerFactory> factories = new ArrayList<>(beans.values());
AnnotationAwareOrderComparator.sort(factories);
this.eventListenerFactories = factories;
}
未完待续......
源码学习笔记:https://github.com/shenjianeng/spring-code-study
欢迎关注公众号:

Spring5源码解析4-refresh方法之invokeBeanFactoryPostProcessors的更多相关文章
- Spring5源码解析-Spring框架中的单例和原型bean
Spring5源码解析-Spring框架中的单例和原型bean 最近一直有问我单例和原型bean的一些原理性问题,这里就开一篇来说说的 通过Spring中的依赖注入极大方便了我们的开发.在xml通过& ...
- Spring5源码解析-论Spring DispatcherServlet的生命周期
Spring Web框架架构的主要部分是DispatcherServlet.也就是本文中重点介绍的对象. 在本文的第一部分中,我们将看到基于Spring的DispatcherServlet的主要概念: ...
- Spring源码解析之八finishBeanFactoryInitialization方法即初始化单例bean
Spring源码解析之八finishBeanFactoryInitialization方法即初始化单例bean 七千字长文深刻解读,Spirng中是如何初始化单例bean的,和面试中最常问的Sprin ...
- 多线程爬坑之路-Thread和Runable源码解析之基本方法的运用实例
前面的文章:多线程爬坑之路-学习多线程需要来了解哪些东西?(concurrent并发包的数据结构和线程池,Locks锁,Atomic原子类) 多线程爬坑之路-Thread和Runable源码解析 前面 ...
- [Java多线程]-Thread和Runable源码解析之基本方法的运用实例
前面的文章:多线程爬坑之路-学习多线程需要来了解哪些东西?(concurrent并发包的数据结构和线程池,Locks锁,Atomic原子类) 多线程爬坑之路-Thread和Runable源码解析 前面 ...
- Spring5源码解析_IOC之容器的基本实现
前言: 在分析源码之前,我们简单回顾一下SPring核心功能的简单使用: 容器的基本用法 Bean是Spring最核心的东西,Spring就像是一个大水桶,而Bean就是水桶中的水,水桶脱离了水就没有 ...
- 一文带你解读Spring5源码解析 IOC之开启Bean的加载,以及FactoryBean和BeanFactory的区别。
前言 通过往期的文章我们已经了解了Spring对XML配置文件的解析,将分析的信息组装成BeanDefinition,并将其保存到相应的BeanDefinitionRegistry中,至此Spring ...
- Spring5源码解析2-register方法注册配置类
接上回已经讲完了this()方法,现在来看register(annotatedClasses);方法. // new AnnotationConfigApplicationContext(AppCon ...
- Spring5源码解析3-refresh方法初探
接上回分析完register(annotatedClasses);后,现在来看一下refresh();方法. // new AnnotationConfigApplicationContext(App ...
随机推荐
- CentOS 7怎么删除mariadb
参考链接:https://www.cnblogs.com/ytkah/p/10876824.html
- 基于python的yaml配置文件使用方法
一.介绍 YAML是一种简洁的非标记语言 YAML以数据为中心,使用空白.缩进.分行组织数据,从而使表达更加简洁易懂 二.基本规则 大小写敏感 使用缩进表示层级关系 禁止使用Tab缩进,只能使用空格键 ...
- Linux下MySQL数据库的my.cnf配置文件,解决中文乱码问题
系统 CentOS 7.7 MySQL - 5.7.28文件放置目录:/etc/文件权限:644解决问题:存储中文数据乱码 # For advice on how to change settings ...
- (五十七)c#Winform自定义控件-传送带(工业)-HZHControls
官网 http://www.hzhcontrols.com 前提 入行已经7,8年了,一直想做一套漂亮点的自定义控件,于是就有了本系列文章. GitHub:https://github.com/kww ...
- Erlang/Elixir精选-第3期(20191216)
2019年,Erlang社区在应用层上除了aeternity区块链让人印象深刻(Killer App)外,就没有特别出彩的应用出现.在Web,IoT,MessageQueue这些成熟领域,已经有相当成 ...
- canvas绘制星星和月亮
用变量的方式绘制一个五角星,首先求五角星十个顶点的坐标. 可以把每个五角星看成外顶点用一个大圆绘制,内顶点用小圆绘制.在坐标系(0deg)下,根据每个顶点的角度和圆的半径求得x,y. 而每个大顶点相差 ...
- 【一】Gradle 初识
1.Gradle和Maven的对比 gradle 使用groovy语言,可以进行逻辑判断,maven基于xml,无法进行逻辑判断. gradle 可以在一个项目中,根据需求,生成2个不同的jar, m ...
- raspberry-gpio-python(树莓派GPIO与Python编程)
国外的设计接口设计得很棒,包括问题:读脏与防抖,还包括读这个数据提供了两种方式,一种是阻塞等待方式,还有一种是回调函数,前一种是通讯中常用的方式,后一种来自系统架构设计的整体性考虑.这种硬件接口设计的 ...
- 如何在文本编辑器中实现时间复杂度O(n/m)的搜索功能? BM算法
//字符串匹配 public class StringCmp { //约定:A主串长 n ,B模式串 长m.要求:在A串中找到B串匹配的下标 //BM算法:从B串和A串尾部开始比较,希望一次将B串向后 ...
- AcWing 13. 找出数组中重复的数字
习题地址 https://www.acwing.com/solution/acwing/content/2919/. 题目描述给定一个长度为 n 的整数数组 nums,数组中所有的数字都在 0∼n−1 ...