目录
本节将继续按照refresh()方法中的执行顺序,分析BeanPostProcessor的注册过程。
1. BeanPostProcessor是什么
public interface BeanPostProcessor {
default Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
return bean;
}
default Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
return bean;
}
}
它是Spring提供的一种干预bean实例化过程的一种扩展方式。实现类可以重写postProcessBeforeInitialization和postProcessAfterInitialization方法,以干预bean的实例化结果。介绍BeanPostProcessor具体应用文章很多,读者可以自行搜索,本文主要从源码的角度介绍BeanPostProcessor的注册过程。了解BeanPostProcessor的作用原理,是深入理解Spring AOP实现原理的关键。
| postProcessBeforeInitialization | 作用于bean实例化方法之后,init初始化方法之前。 |
| postProcessBeforeInitialization | 作用于已经bean已经init初始化方法执行完成之后。 |
2. 流程详解
public void refresh() throws BeansException, IllegalStateException {
synchronized (this.startupShutdownMonitor) {
// 为刷新容器前做准备,没什么干货,略过。
prepareRefresh();
// 简单理解为获得bean工厂DefaultListableBeanFactory对象即可。
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
// 为bean工厂加装一些设备,使其在后续繁杂的bean制造过程中能游刃有余
prepareBeanFactory(beanFactory);
try {
// 空壳方法,为以后Spring扩展预留,略过
postProcessBeanFactory(beanFactory);
// 对BeanFactoryPostProcessor的注册和回调方法执行
invokeBeanFactoryPostProcessors(beanFactory);
// 注册bean的后置处理器,使得bean工厂可以干预bean的实例化过程
registerBeanPostProcessors(beanFactory);
// 国际化(略过)
initMessageSource();
// 初始化Application事件的广播器
initApplicationEventMulticaster();
// Initialize other special beans in specific context subclasses.
onRefresh();
// 注册事件监听器
registerListeners();
// 实例化non-lazy的singleton bean
finishBeanFactoryInitialization(beanFactory);
// Last step: publish corresponding event.
finishRefresh();
}
finally {
// Reset common introspection caches in Spring's core, since we
// might not ever need metadata for singleton beans anymore...
resetCommonCaches();
}
}
}
refresh()-->registerBeanPostProcessors(beanFactory)-->PostProcessorRegistrationDelegate.registerBeanPostProcessors(beanFactory, this)。跳过流程中的包装方法,直接进入干活的最终方法。
public static void registerBeanPostProcessors(
Conf

本文详细介绍了Spring中BeanPostProcessor的注册过程,包括其作用、流程详解以及在Spring AOP实现中的关键地位。通过分析`refresh()`方法,解释了如何将BeanPostProcessor实例化并分类,最后注册到bean工厂,以实现对bean实例化过程的干预。
最低0.47元/天 解锁文章
670

被折叠的 条评论
为什么被折叠?



