Spring扩展——BeanPostProcessor(BPP)
BeanPostProcess简介
在Spring中 BeanPostProcessor 是一个非常重要的接口,它用于在每个bean对象初始化前后修改Bean的属性信息,比如我们最常用的@Autowired注解,在内部处理的时候,是通过一个AutowiredAnnotationBeanPostProcessor类来对bean的属性进行自动注入的,而AutowiredAnnotationBeanPostProcessor也是 BeanPostProcessor的一个实现类。它在createBean的时候会被调用。
1. Spring createBean基本流程图
在Spring中创建Bean对象,我们可以把它看作是两个过程
- 实例化(Spring中通过反射工具进行实例化对象,并将属性设为默认值)
- 初始化(Spring中在初始化前化给属性进行注入操作)

Bean初始化过程

2. BeanPostProcess接口定义
public interface BeanPostProcessor {
/**
* 初始化方法调用前要进行的处理逻辑
*/
@Nullable
default Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
return bean;
}
/**
* 在初始化方法指定后要进行的处理逻辑
*/
@Nullable
default Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
return bean;
}
}
它提供了两个方法,一个前置和后置的处理方法,在bean对象实例化前后分别被调用,并会传入一个将要被处理的bean对象,从上面图中我们可以看出,BeanPostProcessor的before 和 after是在init-method前后调用的,我们一起来看一下,createBean的时候这一部分的源码,在createBean的时候,会调用 doCreateBean,所以真正核心的创建流程在doCreateBean方法中
3. doCreateBean (singleton bean)
protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final @Nullable Object[] args)
throws BeanCreationException {
// Instantiate the bean.
BeanWrapper instanceWrapper = null;
if (mbd.isSingleton()) {
instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
}
if (instanceWrapper == null) {
//实例化
instanceWrapper = createBeanInstance(beanName, mbd, args);
}
final Object bean = instanceWrapper.getWrappedInstance();
Class<?> beanType = instanceWrapper.getWrappedClass();
if (beanType != NullBean.class) {
mbd.resolvedTargetType = beanType;
}
// Allow post-processors to modify the merged bean definition.
synchronized (mbd.postProcessingLock) {
if (!mbd.postProcessed) {
try {
applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
}
catch (Throwable ex) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"Post-processing of merged bean definition failed", ex);
}
mbd.postProcessed = true;
}
}
// Eagerly cache singletons to be able to resolve circular references
// even when triggered by lifecycle interfaces like BeanFactoryAware.
boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences &&
isSingletonCurrentlyInCreation(beanName));
if (earlySingletonExposure) {
if (logger.isTraceEnabled()) {
logger.trace("Eagerly caching bean '" + beanName +
"' to allow for resolving potential circular references");
}
addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
}
// Initialize the bean instance.
Object exposedObject = bean;
try {
populateBean(beanName, mbd, instanceWrapper);
exposedObject = initializeBean(beanName, exposedObject, mbd);
}
catch (Throwable ex) {
if (ex instanceof BeanCreationException && beanName.equals(((BeanCreationException) ex).getBeanName())) {
throw (BeanCreationException) ex;
}
else {
throw new BeanCreationException(
mbd.getResourceDescription(), beanName, "Initialization of bean failed", ex);
}
}
if (earlySingletonExposure) {
Object earlySingletonReference = getSingleton(beanName, false);
if (earlySingletonReference != null) {
if (exposedObject == bean) {
exposedObject = earlySingletonReference;
}
else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) {
String[] dependentBeans = getDependentBeans(beanName);
Set<String> actualDependentBeans = new LinkedHashSet<>(dependentBeans.length);
for (String dependentBean : dependentBeans) {
if (!removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) {
actualDependentBeans.add(dependentBean);
}
}
if (!actualDependentBeans.isEmpty()) {
throw new BeanCurrentlyInCreationException(beanName,
"Bean with name '" + beanName + "' has been injected into other beans [" +
StringUtils.collectionToCommaDelimitedString(actualDependentBeans) +
"] in its raw version as part of a circular reference, but has eventually been " +
"wrapped. This means that said other beans do not use the final version of the " +
"bean. This is often the result of over-eager type matching - consider using " +
"'getBeanNamesOfType' with the 'allowEagerInit' flag turned off, for example.");
}
}
}
}
// Register bean as disposable.
try {
registerDisposableBeanIfNecessary(beanName, bean, mbd);
}
catch (BeanDefinitionValidationException ex) {
throw new BeanCreationException(
mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex);
}
return exposedObject;
}
在以上创建过程中,我们可以看到几个重要的方法
1. createBeanInstance 实例化Bean对象
2. populateBean 为Bean对象填充属性
3. initializeBean 初始化bean对象
4. 初始化Bean对象
在initializeBean 方法中
protected Object initializeBean(final String beanName, final Object bean, @Nullable RootBeanDefinition mbd) {
if (System.getSecurityManager() != null) {
AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
invokeAwareMethods(beanName, bean);
return null;
}, getAccessControlContext());
}
else {
invokeAwareMethods(beanName, bean);
}
Object wrappedBean = bean;
if (mbd == null || !mbd.isSynthetic()) {
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()) {
wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
}
return wrappedBean;
}
首先会调用invokeAwareMethods方法,处理几个特殊的aware接口(BeanNameAware、BeanClassLoaderAware、BeanFactoryAware),以便在后面的处理过程中可能会使用到,所以提前处理
其它的Aware接口会通过BeanPostProcessor去处理。
重点来了
applyBeanPostProcessorsBeforeInitialization 通过调用此方法去遍历Spring容器中的 BeanPostProcessor,并执行其 postProcessBeforeInitialization 方法
invokeInitMethods 通过调用此方法完成以下的一些操作
- afterPropertiesSet方法的调用
- 调用自定义的init-method方法
applyBeanPostProcessorsAfterInitialization 通过调用此方法去遍历Spring容器中的 BeanPostProcessor,并执行其 postProcessAfterInitialization 方法
在applyBeanPostProcessorsBeforeInitialization中我可以看到我们常用的一些BeanPostProcessor调用
- ApplicationContextAwarePostProcessor 处理我们的几个Spring中提供的Aware接口
EnvironmentAware、EmbeddedValueResolverAware、ResourceLoaderAware、ApplicationEventPublisherAware、MessageSourceAware、ApplicationContextAware - ImportAwareBeanPostProcessor 处理被import注解了的bean对象,并进行递归import bean对象
详细的流程图如下

自定义BeanPostProcessor
需要:自定义一个BeanPostProcessor用于打印输出 每个bean 初始化成功的消息
@Component
public class CustomBeanPostProcessor implements BeanPostProcessor {
/**
* BeanPostProcessor 接口里有默认方法,默认直接将bean返回
*
* @param bean the new bean instance
* @param beanName the name of the bean
* @return
* @throws BeansException
*/
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
return bean;
}
/**
* 在后置处理器中,可以对bean对象进行修改操作
* 1. 可以返回其代理对象
* <p>
* 我们这里只输出一下bean创建成功的消息
*
* @param bean the new bean instance
* @param beanName the name of the bean
* @return
* @throws BeansException
*/
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
System.out.println(beanName + " init successful");
return bean;
}
另外一篇里面也有关于BeanPostProcessor的扩展——https://www.cnblogs.com/yanchuanbin/p/14582813.html
Spring扩展——BeanPostProcessor(BPP)的更多相关文章
- Spring中BeanPostProcessor
Spring中BeanPostProcessor 前言: 本文旨在介绍Spring动态配置数据源的方式,即对一个DataSource的配置诸如jdbcUrl,user,password,driverC ...
- spring中BeanPostProcessor之一:InstantiationAwareBeanPostProcessor(01)
在spring中beanPostProcessor绝对是开天辟地的产物,给了程序员很多自主权,beanPostProcessor即常说的bean后置处理器. 一.概览 先来说下Instantiatio ...
- spring扩展点整理
本文转载自spring扩展点整理 背景 Spring的强大和灵活性不用再强调了.而灵活性就是通过一系列的扩展点来实现的,这些扩展点给应用程序提供了参与Spring容器创建的过程,好多定制化的东西都需要 ...
- Spring 的 BeanPostProcessor接口实现
今天学习了一下Spring的BeanPostProcessor接口,该接口作用是:如果我们需要在Spring容器完成Bean的实例化,配置和其他的初始化后添加一些自己的逻辑处理,我们就可以定义一个或者 ...
- spring扩展点之三:Spring 的监听事件 ApplicationListener 和 ApplicationEvent 用法,在spring启动后做些事情
<spring扩展点之三:Spring 的监听事件 ApplicationListener 和 ApplicationEvent 用法,在spring启动后做些事情> <服务网关zu ...
- spring扩展点之二:spring中关于bean初始化、销毁等使用汇总,ApplicationContextAware将ApplicationContext注入
<spring扩展点之二:spring中关于bean初始化.销毁等使用汇总,ApplicationContextAware将ApplicationContext注入> <spring ...
- spring中BeanPostProcessor之三:InitDestroyAnnotationBeanPostProcessor(01)
在<spring中BeanPostProcessor之二:CommonAnnotationBeanPostProcessor(01)>一文中,分析到在调用CommonAnnotationB ...
- spring中BeanPostProcessor之四:AutowiredAnnotationBeanPostProcessor(01)
在<spring中BeanPostProcessor之二:CommonAnnotationBeanPostProcessor(01)>中分析了CommonAnnotationBeanPos ...
- spring扩展点之一:BeanFactoryPostProcessor和BeanPostProcessor
一.BeanFactoryPostProcessor和BeanPostProcessor的区别 BeanFactoryPostProcessor和BeanPostProcessor都是spring初始 ...
- Spring的BeanPostProcessor和BeanFactoryPostProcessor区别
Spring提供了两种后处理bean的扩展接口,分别为BeanPostProcessor和BeanFactoryPostProcessor,这两者在使用上是有所区别的. BeanPostProcess ...
随机推荐
- 科学地花钱:基于端智能的在线红包分配方案 (CIKM2020)
简介: 红包是电商平台重要的用户运营手段,本文将介绍1688基于端智能技术开发的two-stage红包分发方案.这一方案持续在线上生效,相较于原有算法有明显提升. 一.前言 本文是作者在1688进行新 ...
- 如何使用Delta Lake构建批流一体数据仓库
简介:Delta Lake是一个开源存储层,它为数据湖带来了可靠性.Delta Lake提供了ACID事务.可扩展的元数据处理,并统一了流式处理和批处理数据处理.Delta-Lake运行在现有数据湖 ...
- 大数据时代下,App数据隐私安全你真的了解么?
简介:你是否有过这样的经历:你和朋友聊天表达你近期想要购买某件商品,第二天当你打开某购物软件时,平台向你推送的商品正是你想要购买的:或者,你是否接到过陌生来电,他们准确的报出了你的名字和年龄.... ...
- Quick BI产品核心功能大图(四):Quick引擎加速--十亿数据亚秒级分析
简介: 随着数字化进程的深入,数据应用的价值被越来越多的企业所重视.基于数据进行决策分析是应用价值体现的重要场景,不同行业和体量的公司广泛依赖BI产品制作报表.仪表板和数据门户,以此进行决策分析. ...
- [Go] 选择 Beego 的三个理由
1. 项目支持角度较其它框架考虑的多一些,比如:目录结构的简单约定,内置项目配置读取,内置bee脚手架,热重载特性 等. (实际这些 feature 都可以找到 golang 专精的组件引入起来,效果 ...
- dotnet SemanticKernel 入门 注入日志
使用 SemanticKernel 框架在对接 AI 时,由于使用到了大量的魔法,需要有日志的帮助才好更方便定位问题,本文将告诉大家如何在 SemanticKernel 注入日志 本文属于 Seman ...
- dotnet 性能优化 利用哈希思想优化大对象集合相等判断性能
利用哈希的其中一个思想,相同的对象的哈希值相同,可以用来提升一些大对象集合的进行对象相等判断的性能.大对象的相等判断指的是有某些类型的相等判断需要用到对象的很多属性或字段进行参与判断逻辑才能判断两个对 ...
- 使用openvp*-gui客户端连接多服务端,作为Windows服务部署
背景 多数公司都会用到VPN隧道技术链接服务器,保证服务器的安全,但多数情况下会存在多服务端的情况,这时就有客户端连接多个服务端的必要了,如果每次都要切换配置的话,对于有强迫症的兄弟当然忍不了了 思考 ...
- 【python爬虫案例】用python爬取百度的搜索结果!2023.3发布
目录 一.爬取目标 二.展示结果数据 三.编写爬虫代码 3.1 请求头和cookie 3.2 分析请求地址 3.3 分析页面元素 3.4 获取真实地址 3.5 保存结果数据 四.同步讲解视频 五.附完 ...
- Vben-admin---ApiSelect Invalid prop: type check failed for prop "onUpdate:value". Expected Function, got Array
在basicFrom组件里添加一个ApiSelect, <template #localSearch="{ model, field }"> <ApiSelect ...