Spring IOC源码分析-registerBeanPostProcessors

愿天堂没有BUG

共 8369字,需浏览 17分钟

 ·

2021-08-28 14:51

前言

invokeBeanFactoryPostProcessors 方法主要用于处理 BeanFactoryPostProcessor 接口,而 registerBeanPostProcessors 方法主要用于处理 BeanPostProcessor 接口。

BeanFactoryPostProcessor 和 BeanPostProcessor区别:

  • BeanFactoryPostProcessor 是针对 BeanFactory 的扩展,主要用在 bean 实例化之前,读取 bean 的定义,并可以修改它。

  • BeanPostProcessor 是针对 bean 的扩展,主要用在 bean 实例化之后,执行初始化方法前后。

比如AOP生成代理的功能,就是在被代理类实例化之后去生成代理对象的.

Spring 源码分析系列

  • Spring源码分析-源码阅读环境搭建

  • Spring源码分析-IOC基本概念

  • Spring源码分析-IOC核心组件

  • Spring源码分析-IOC源码分析(一)

  • Spring IOC源码分析-obtainFreshBeanFactory(二)

  • Spring IOC源码分析-invokeBeanFactoryPostProcessors (三)

源码分析

registerBeanPostProcessors 会注册所有的 BeanPostProcessor, 将所有实现了BeanPostProcessor 的类加载到BeanFactory中.

BeanPostProcessor 接口是 Spring 初始化 bean 时对外暴露的扩展点,Spring IoC 容器允许 BeanPostProcessor 在容器初始化 bean 的前后,添加自己的逻辑处理。在 registerBeanPostProcessors 方法只是注册到 BeanFactory 中,具体调用是在 bean 初始化的时候。

registerBeanPostProcessors

public static void registerBeanPostProcessors(
ConfigurableListableBeanFactory beanFactory, AbstractApplicationContext applicationContext)
{

// 1. 找出所有实现 BeanPostProcessor 接口的类
String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanPostProcessor.class, true, false);

// Register BeanPostProcessorChecker that logs an info message when
// a bean is created during BeanPostProcessor instantiation, i.e. when
// a bean is not eligible for getting processed by all BeanPostProcessors.
// BeanPostProcessor 计数
int beanProcessorTargetCount = beanFactory.getBeanPostProcessorCount() + 1 + postProcessorNames.length;
// 2. 添加 BeanPostProcessorChecker , 主要用于记录信息到BeanFactory中
beanFactory.addBeanPostProcessor(new BeanPostProcessorChecker(beanFactory, beanProcessorTargetCount));

// Separate between BeanPostProcessors that implement PriorityOrdered,
// Ordered, and the rest.
// 3. 定义不同的变量用于区分实现PriorityOrdered, Ordered 接口的 BeanPostProcessor 和普通的BeanPostProcessor
// 3.1 priorityOrderedPostProcessors 存储实现PriorityOrdered 接口的BeanPostProcessor
List<BeanPostProcessor> priorityOrderedPostProcessors = new ArrayList<>();
// 3.2 internalPostProcessors 存储Spring内部的BeanPostProcessor
List<BeanPostProcessor> internalPostProcessors = new ArrayList<>();
// 3.3 orderedPostProcessorNames 存储实现Ordered接口BeanPostProcessor 的Name
List<String> orderedPostProcessorNames = new ArrayList<>();
// 3.4 存储普通的BeanPostProcessor 的BeanName
List<String> nonOrderedPostProcessorNames = new ArrayList<>();
// 4. 遍历postProcessorNames
for (String ppName : postProcessorNames) {
// 4.1 实现PriorityOrdered 接口的BeanPostProcessor 处理
if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
priorityOrderedPostProcessors.add(pp);
// 4.2 如果 pp对应Bean实例也实现了 MergedBeanDefinitionPostProcessor接口,则添加到internalPostProcessors
if (pp instanceof MergedBeanDefinitionPostProcessor) {
internalPostProcessors.add(pp);
}
}
else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
// 4.3 实现了Ordered接口, 添加到 orderedPostProcessorNames
orderedPostProcessorNames.add(ppName);
}
else {
// 4.4 普通的 nonOrderedPostProcessorNames
nonOrderedPostProcessorNames.add(ppName);
}
}

// First, register the BeanPostProcessors that implement PriorityOrdered.
// 5. 首先, 注册实现了PriorityOrdered 接口的BeanPostProcessors
// 5.1 排序
sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
// 5.2 注册 registerBeanPostProcessors
registerBeanPostProcessors(beanFactory, priorityOrderedPostProcessors);

// Next, register the BeanPostProcessors that implement Ordered.
// 6. 接下来, 注册实现 Ordered 接口的BeanPostProcessors
List<BeanPostProcessor> orderedPostProcessors = new ArrayList<>(orderedPostProcessorNames.size());
for (String ppName : orderedPostProcessorNames) {
// 6.1 拿到ppName对应的 BeanPostProcessor
BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
// 6.2 添加到orderedPostProcessors 准备执行注册
orderedPostProcessors.add(pp);
if (pp instanceof MergedBeanDefinitionPostProcessor) {
// 6.3 如果pp实例也实现了 MergedBeanDefinitionPostProcessor接口, 添加到 internalPostProcessors
internalPostProcessors.add(pp);
}
}
// 6.4 排序
sortPostProcessors(orderedPostProcessors, beanFactory);
// 6.5 注册 orderedPostProcessors
registerBeanPostProcessors(beanFactory, orderedPostProcessors);

// Now, register all regular BeanPostProcessors.
// 7. 注册普通的 BeanPostProcessors
List<BeanPostProcessor> nonOrderedPostProcessors = new ArrayList<>(nonOrderedPostProcessorNames.size());
for (String ppName : nonOrderedPostProcessorNames) {
BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
nonOrderedPostProcessors.add(pp);
if (pp instanceof MergedBeanDefinitionPostProcessor) {
internalPostProcessors.add(pp);
}
}
registerBeanPostProcessors(beanFactory, nonOrderedPostProcessors);

// Finally, re-register all internal BeanPostProcessors.
// 8. 最后,重新注册内部 internalPostProcessors,(相当于移动到链表的末尾)
// 8.1 排序
sortPostProcessors(internalPostProcessors, beanFactory);
// 8.2 注册 internalPostProcessors
registerBeanPostProcessors(beanFactory, internalPostProcessors);

// Re-register post-processor for detecting inner beans as ApplicationListeners,
// moving it to the end of the processor chain (for picking up proxies etc).
// 9. 重新注册 ApplicationListenerDetector,主要目的是移动到处理链的末尾
beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(applicationContext));
}
复制代码

priorityOrderedPostProcessors

这个比较简单就不说了

registerBeanPostProcessors

/**
* Register the given BeanPostProcessor beans.
*/

private static void registerBeanPostProcessors(
ConfigurableListableBeanFactory beanFactory, List<BeanPostProcessor> postProcessors)
{

for (BeanPostProcessor postProcessor : postProcessors) {
beanFactory.addBeanPostProcessor(postProcessor);
}
}
复制代码

beanFactory#addBeanPostProcessor

@Override
public void addBeanPostProcessor(BeanPostProcessor beanPostProcessor) {
Assert.notNull(beanPostProcessor, "BeanPostProcessor must not be null");
// Remove from old position, if any
// 如果存在则移除
this.beanPostProcessors.remove(beanPostProcessor);
// Track whether it is instantiation/destruction aware
// 设置标识 hasInstantiationAwareBeanPostProcessors
if (beanPostProcessor instanceof InstantiationAwareBeanPostProcessor) {
this.hasInstantiationAwareBeanPostProcessors = true;
}
// 设置标识 hasDestructionAwareBeanPostProcessors
if (beanPostProcessor instanceof DestructionAwareBeanPostProcessor) {
this.hasDestructionAwareBeanPostProcessors = true;
}
// Add to end of list
// beanPostProcessor 添加到链表中
this.beanPostProcessors.add(beanPostProcessor);
}
复制代码

扩展案例

定义MyBeanPostProcessor实现 BeanPostProcessor 接口

public class MyBeanPostProcessor implements BeanPostProcessor, PriorityOrdered {

@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
System.out.println("Bean 实例化之前... " + beanName);
return bean;
}

@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
System.out.println("Bean 实例化之后..." + beanName);
return bean;
}

@Override
public int getOrder() {
return 0;
}
}
复制代码

定义User对象, 通过Configuration 定义Bean

// User对象
public class User {
private String name;

public User() {
System.out.println("User 对象实例化");
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}
}

// 定义Bean
@Configuration
public class BeanConfig {

@Bean
public User user() {
return new User();
}

@Bean
public MyPostProcessorBean myPostProcessorBean() {
return new MyPostProcessorBean();
}
}
复制代码

单元测试

public class BeanPostProcessorTest {

@Test
public void test() {
ApplicationContext context =
new AnnotationConfigApplicationContext(BeanConfig.class);
}
}
复制代码

结果

注意两个比较容易踩的坑

  1. BeanPostProcessor依赖的bean,不会执行BeanPostProcessor的方法

  2. BeanPostProcessor以及依赖的bean无法使用AOP

最后

就这样把, Spring概念太多, 需要多梳理清楚这些点的差异, 多画图.


作者:伯仁
链接:https://juejin.cn/post/7000410020739284999
来源:掘金
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。



浏览 16
点赞
评论
收藏
分享

手机扫一扫分享

分享
举报
评论
图片
表情
推荐
点赞
评论
收藏
分享

手机扫一扫分享

分享
举报