Spring扩展点之BeanPostProcessor
前言
BeanPostProcessor接口是Spring中一个非常重要的接口,它的接口定义如下
public interface BeanPostProcessor {
Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException;
Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException;
}
当你实现了这个接口的时候,Spring会保证在每一个bean对象初始化方法调用之前调用postProcessBeforeInitialization方法,在初始化方法调用之后调用postProcessAfterInitialization
BeanPostProcessor的注册
看过我之前写的IOC源码分析系列文章的同学应该对这个都比较有印象
)
Spring在执行到这的时候会把所有实现BeanPostProcessor接口的实现类都注册到BeanFactory中,一起来看一下实现的细节
protected void registerBeanPostProcessors(ConfigurableListableBeanFactory beanFactory) {
PostProcessorRegistrationDelegate.registerBeanPostProcessors(beanFactory, this);
}
public static void registerBeanPostProcessors(
ConfigurableListableBeanFactory beanFactory, AbstractApplicationContext applicationContext) {
//获取所有BeanPostProcessor的实现类
String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanPostProcessor.class, true, false);
int beanProcessorTargetCount = beanFactory.getBeanPostProcessorCount() + 1 + postProcessorNames.length;
beanFactory.addBeanPostProcessor(new BeanPostProcessorChecker(beanFactory, beanProcessorTargetCount));
// 这里把实现PriorityOrdered接口,Ordered 接口的BeanPostProcessors 和其他类型的BeanPostProcessors 区分开
List<BeanPostProcessor> priorityOrderedPostProcessors = new ArrayList<>();
List<BeanPostProcessor> internalPostProcessors = new ArrayList<>();
List<String> orderedPostProcessorNames = new ArrayList<>();
List<String> nonOrderedPostProcessorNames = new ArrayList<>();
for (String ppName : postProcessorNames) {
if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
priorityOrderedPostProcessors.add(pp);
if (pp instanceof MergedBeanDefinitionPostProcessor) {
internalPostProcessors.add(pp);
}
}
else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
orderedPostProcessorNames.add(ppName);
}
else {
nonOrderedPostProcessorNames.add(ppName);
}
}
//对实现了PriorityOrdered接口的按优先级排序
sortPostProcessors(beanFactory, priorityOrderedPostProcessors);
//这里就是注册了,下面会说
registerBeanPostProcessors(beanFactory, priorityOrderedPostProcessors);
List<BeanPostProcessor> orderedPostProcessors = new ArrayList<>();
for (String ppName : orderedPostProcessorNames) {
BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
orderedPostProcessors.add(pp);
if (pp instanceof MergedBeanDefinitionPostProcessor) {
internalPostProcessors.add(pp);
}
}
sortPostProcessors(beanFactory, orderedPostProcessors);
//注册
registerBeanPostProcessors(beanFactory, orderedPostProcessors);
List<BeanPostProcessor> nonOrderedPostProcessors = new ArrayList<>();
for (String ppName : nonOrderedPostProcessorNames) {
BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
nonOrderedPostProcessors.add(pp);
if (pp instanceof MergedBeanDefinitionPostProcessor) {
internalPostProcessors.add(pp);
}
}
//注册
registerBeanPostProcessors(beanFactory, nonOrderedPostProcessors);
// 最后注册常规的
sortPostProcessors(beanFactory, internalPostProcessors);
registerBeanPostProcessors(beanFactory, internalPostProcessors);
beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(applicationContext));
}
可以看到上方的代码就是把这些BeanPostProcessor分为了几类,然后分别根据规则排序后注册进BeanFactory中,而BeanFactory中其实就只是维护了一个BeanPostProcessor的列表而已
private final List<BeanPostProcessor> beanPostProcessors = new ArrayList();
private static void registerBeanPostProcessors(
ConfigurableListableBeanFactory beanFactory, List<BeanPostProcessor> postProcessors) {
for (BeanPostProcessor postProcessor : postProcessors) {
beanFactory.addBeanPostProcessor(postProcessor);
}
}
public void addBeanPostProcessor(BeanPostProcessor beanPostProcessor) {
Assert.notNull(beanPostProcessor, "BeanPostProcessor must not be null");
this.beanPostProcessors.remove(beanPostProcessor);
this.beanPostProcessors.add(beanPostProcessor);
if (beanPostProcessor instanceof InstantiationAwareBeanPostProcessor) {
this.hasInstantiationAwareBeanPostProcessors = true;
}
if (beanPostProcessor instanceof DestructionAwareBeanPostProcessor) {
this.hasDestructionAwareBeanPostProcessors = true;
}
}
执行原理
我们知道Bean的初始化是在定义在容器的刷新过程中,而具体的实现则是由AbstractAutowireCapableBeanFactory.initializeBean()方法完成的。在这个方法中就包含了BeanPostProcessor的调用逻辑
protected Object initializeBean(final String beanName, final Object bean, RootBeanDefinition mbd) {
if (System.getSecurityManager() != null) {
AccessController.doPrivileged(new PrivilegedAction<Object>() {
@Override
public Object run() {
invokeAwareMethods(beanName, bean);
return null;
}
}, getAccessControlContext());
}
else {
invokeAwareMethods(beanName, bean);
}
Object wrappedBean = bean;
if (mbd == null || !mbd.isSynthetic()) {
// BeanPostProcessors 的Before 方法
wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
}
try {
// 调用初始化方法
invokeInitMethods(beanName, wrappedBean, mbd);
}
catch (Throwable ex) {
throw new BeanCreationException(
(mbd != null ? mbd.getResourceDescription() : null),
beanName, "Invocation of init method failed", ex);
}
if (mbd == null || !mbd.isSynthetic()) {
// BeanPostProcessors 的After方法
wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
}
return wrappedBean;
}
而这里面的执行逻辑我们也可以猜到,无非就是循环遍历所有的BeanPostProcessor,然后一一执行
public Object applyBeanPostProcessorsBeforeInitialization(Object existingBean, String beanName)
throws BeansException {
Object result = existingBean;
for (BeanPostProcessor beanProcessor : getBeanPostProcessors()) {
result = beanProcessor.postProcessBeforeInitialization(result, beanName);
if (result == null) {
return result;
}
}
return result;}
其中applyBeanPostProcessorsAfterInitialization的实现内容跟这个是一样的
但是这里面有一个主意的点,那就是如果具体的实现一但返回null,那么就会跳出for循环,后面的就得不到机会执行了
常见用例
查看这个接口的继承体系,可以看到这个接口的实现类是非常多的,各个实现类的功能如果感兴趣大家可以去慢慢挖掘一下

Spring扩展点之BeanPostProcessor的更多相关文章
- Spring扩展点之Aware接口族
引言 Spring中提供了各种Aware接口,方便从上下文中获取当前的运行环境,比较常见的几个子接口有:BeanFactoryAware,BeanNameAware,ApplicationContex ...
- Spring扩展点-v5.3.9
Spring 扩展点 **本人博客网站 **IT小神 www.itxiaoshen.com 官网地址****:https://spring.io/projects/spring-framework T ...
- Spring扩展点之BeanFactoryPostProcessor
前言 BeanFactoryPostProcessor接口是Spring中一个非常重要的接口,它的接口定义如下 public interface BeanFactoryPostProcessor { ...
- Spring扩展点之FactoryBean接口
前言 首先看一下接口定义 public interface FactoryBean<T> { /** * 返回对象实例 */ @Nullable T getObject() throws ...
- spring扩展点之PropertyPlaceholderConfigurer
原理机制讲解 https://leokongwq.github.io/2016/12/28/spring-PropertyPlaceholderConfigurer.html 使用时多个配置讲解 ht ...
- Spring中的扩展点
Spring作为一个常用的IOC框架,在设计上预留了很多的扩展点,很多第三方开源框架,包括Spring自身也是基于这些扩展点实现的,这很好的体现了对修改关闭.对扩展开放的原则.总的来说Spring的扩 ...
- Spring系列14:IoC容器的扩展点
Spring系列14:IoC容器的扩展点 回顾 知识需要成体系地学习,本系列文章前后有关联,建议按照顺序阅读.上一篇我们详细介绍了Spring Bean的生命周期和丰富的扩展点,没有阅读的强烈建议先阅 ...
- 三万字盘点Spring/Boot的那些常用扩展点
大家好,我是三友. Spring对于每个Java后端程序员来说肯定不陌生,日常开发和面试必备的.本文就来盘点Spring/SpringBoot常见的扩展点,同时也来看看常见的开源框架是如何基于这些扩展 ...
- Spring Boot 中如何使用 Dubbo Activate 扩展点
摘要: 原创出处 www.bysocket.com 「泥瓦匠BYSocket 」欢迎转载,保留摘要,谢谢! 『 公司的核心竞争力在于创新 – <启示录> 』 继续上一篇:< Spri ...
随机推荐
- Spring Junit 测试样例
SpringMVC 框架下的junit测试方式 package com.sixeco.user.controller; import org.apache.logging.log4j.LogManag ...
- fd (int)读写文件
#include <string.h> #include <stdio.h> #include <fcntl.h> int main() { char *p1 = ...
- pdfium:创建CreateNewDoc
CreateNewDoc //创建文档 https://github.com/PureFusionOS/android_external_pdfium/blob/040b899a933cdb37 ...
- c# 第三节 vs的安装
本节内容: 学会安装vs 一:下载 地址:http://down.lansedongli.com/view/30323.html 二.vs2015支持的操作系统 三.vs2015的硬件要求 四.安装 ...
- Mac环境下 jieba 配置记录
在终端里输入: pip3 install jieba -i http://pypi.douban.com/simple --trusted-host pypi.douban.com
- day37_8_21表的查询
一.语法 表的查询一般使用select关键字,配合where筛选.顺序如下: # 先后顺序 from where select 二.where约束条件 首先先建立表: create table emp ...
- day5_7.3 数据类型的各种函数操作
昨日补充: 1.在代码的编写中,总会有一些分支编写不出来,为了不影响整个系统的跑动,可以使用pass关键字进行跳过.如 count=0 while count<10: if count<5 ...
- 怎么安装python3
解压 这个压缩包 2.把解压后的python文件夹所在的路径配置到环境变量 3.鼠标移动到计算机上---右键---属性----高级系统设置---环境变量,打开如下界面 4.在系统变量里选择pa ...
- 03-人脸识别-基于MTCNN,显示5个人脸特征
import tensorflow as tf import numpy as np import cv2 import detect_face import matplotlib.pyplot as ...
- LG2053/BZOJ1070 「SCOI2007」修车 费用流
问题描述 LG2053 BZOJ1070 题解 将\(m\)个修理工拆为\(n \times m\)个,将修理工和车辆看做二分图,连出一个完全二分图. 边流量为\(1\),费用为时间,费用流即可. \ ...