Spring在我们目前的开发中基本上必不可少,绝大多数的公司都使用Spring框架作为开发的基础架构,那么我们有必要了解Spring是怎么工作的,以及如何在工作中使用并扩展Spring。今天我们就先来讲解Spring中一个非常重要的概念:后置处理器。
Spring中有两种非常重要的后置处理器:
其中Bean工厂后置处理器就是本节要讲的,它们会在Spring启动过程中,在实例化bean之前执行,它们主要用来扫描出后续需要进行实例化的bean,并注册成BeanDifinition,如Spring整合mabatis,具体可以参考我的另外两篇博文。
Spring继承mybatis源码分析(一)
Spring继承mybatis源码分析(二)
大家先看下面这段代码,我们刚学Spring的时候,想要初始化一个Spring容器,首先会新建一个ApplicationContext上下文环境。
public static void main(String[] args) throws NoSuchMethodException {
AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext();
//ClassPathXmlApplicationContext xmlAc = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
ac.register(AppConfig.class);
ac.refresh();
}
如果是采用XML配置的方式,我们会使用ClassPathXmlApplicationContext,并且在配置文件中加上
public void refresh() throws BeansException, IllegalStateException {
synchronized (this.startupShutdownMonitor) {
//
prepareRefresh();
// Tell the subclass to refresh the internal bean factory.
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
// 准备bean工厂,主要做了以下几点
// 1. 设置了bean的类加载器
// 2. 添加了ApplicationContextAwareProcessor,ApplicationListenerDetector的BeanPostProcessor
// 3. 添加了部分默认的Spring系统bean依赖
// 4. 添加了表达式解析器
prepareBeanFactory(beanFactory);
try {
// 本类没做任何事,留作子类扩展用
postProcessBeanFactory(beanFactory);
// 执行BeanFactoryPostProcessor,
invokeBeanFactoryPostProcessors(beanFactory);
// 注册Spring自带的扫描出来的,以及系统自带的BeanPostProcessor,并排序
registerBeanPostProcessors(beanFactory);
// 初始化国际化相关的内容
initMessageSource();
// 初始事件广播器
initApplicationEventMulticaster();
// 注册其他bean或者其他操作,提供给子类扩展,默认不做任何事
onRefresh();
// 添加监听器
registerListeners();
// 实例化bean
finishBeanFactoryInitialization(beanFactory);
// 执行LifecycleProcessor,发布ContextRefreshed事件
finishRefresh();
}
catch (BeansException ex) {
if (logger.isWarnEnabled()) {
logger.warn("Exception encountered during context initialization - " +
"cancelling refresh attempt: " + ex);
}
// Destroy already created singletons to avoid dangling resources.
destroyBeans();
// Reset 'active' flag.
cancelRefresh(ex);
// Propagate exception to caller.
throw ex;
}
finally {
// Reset common introspection caches in Spring's core, since we
// might not ever need metadata for singleton beans anymore...
resetCommonCaches();
}
}
}
我们来看一下Spring中最重要的ConfigurationClassPostProcessor这个类的类图,
具体的详细说明见代码
我们这里要讲的ConfigurationClassPostProcessor会在invokeBeanFactoryPostProcessors()方法中执行。
public static void invokeBeanFactoryPostProcessors(
ConfigurableListableBeanFactory beanFactory, List<BeanFactoryPostProcessor> beanFactoryPostProcessors) {
// 已经执行过的BeanFactoryPostProcessor的beanName
Set<String> processedBeans = new HashSet<>();
// 默认是DefaultListableBeanFactory,实现了BeanDefinitionRegistry
if (beanFactory instanceof BeanDefinitionRegistry) {
BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
List<BeanFactoryPostProcessor> regularPostProcessors = new ArrayList<>();
List<BeanDefinitionRegistryPostProcessor> registryProcessors = new ArrayList<>();
// 遍历程序员自己手动添加的beanFactoryPostProcessors, 以及spring如SpringBoot自己最开始添加的beanFactoryPostProcessors
// 如果属于BeanDefinitionRegistryPostProcessor,则执行postProcessBeanDefinitionRegistry
// ac.addBeanFactoryPostProcessor()
for (BeanFactoryPostProcessor postProcessor : beanFactoryPostProcessors) {
if (postProcessor instanceof BeanDefinitionRegistryPostProcessor) {
BeanDefinitionRegistryPostProcessor registryProcessor =
(BeanDefinitionRegistryPostProcessor) postProcessor;
registryProcessor.postProcessBeanDefinitionRegistry(registry);
registryProcessors.add(registryProcessor);
}
else {
regularPostProcessors.add(postProcessor);
}
}
// 首先执行实现了PriorityOrdered,BeanDefinitionRegistryPostProcessor的实例的postProcessBeanDefinitionRegistry方法
// 这里我们就会执行本次说的ConfigurationClassPostProcessor类,这个类负责扫描配置类
List<BeanDefinitionRegistryPostProcessor> currentRegistryProcessors = new ArrayList<>();
// 获取到所有的BeanDefinitionRegistryPostProcessor类型的bean
String[] postProcessorNames =
beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
for (String ppName : postProcessorNames) {
if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
// 执行过的加入,后续先判断有没有执行过
processedBeans.add(ppName);
}
}
// 排序
sortPostProcessors(currentRegistryProcessors, beanFactory);
// 实现了BeanDefinitionRegistryPostProcessor的类加入到registryProcessors,后续需要调用BeanFactoryPostProcessor的postProcessBeanFactory方法
registryProcessors.addAll(currentRegistryProcessors);
// 执行postProcessBeanDefinitionRegistry方法,在该处,将执行ConfigurationClassPostProcessor,对配置类进行扫描,并注册BeanDifinition
invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
currentRegistryProcessors.clear();
// 按上面的流程执行实现了Ordered的BeanDefinitionRegistryPostProcessor
postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
for (String ppName : postProcessorNames) {
// 没有执行过才执行
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);
invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
currentRegistryProcessors.clear();
// 最后执行其他所有的BeanDefinitionRegistryPostProcessor
// while循环判断是否在执行postProcessBeanDefinitionRegistry方法的过程中,又出现了其他的BeanDefinitionRegistryPostProcessor,直到最后没有为止
boolean reiterate = true;
while (reiterate) {
reiterate = false;
postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
for (String ppName : postProcessorNames) {
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();
}
// 执行所有实现了BeanDefinitionRegistryPostProcessor接口的BeanFactoryPostProcessor的postProcessBeanFactory方法
invokeBeanFactoryPostProcessors(registryProcessors, beanFactory);
// 执行所有Spring自带的或者由程序员手动添加的直接继承自BeanFactoryPostProcessor的postProcessBeanFactory方法
invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory);
}
else {
// Invoke factory processors registered with the context instance.
invokeBeanFactoryPostProcessors(beanFactoryPostProcessors, beanFactory);
}
// 获取直接实现了BeanFactoryPostProcessor的beanNames,此处会获取到实现了BeanDefinitionRegistryPostProcessor,但实现了后者的bean已经在processedBeans中,因此不会再次执行
String[] postProcessorNames =
beanFactory.getBeanNamesForType(BeanFactoryPostProcessor.class, true, false);
List<BeanFactoryPostProcessor> priorityOrderedPostProcessors = new ArrayList<>();
List<String> orderedPostProcessorNames = new ArrayList<>();
List<String> nonOrderedPostProcessorNames = new ArrayList<>();
// 分类,实现了PriorityOrdered,Ordered,和没有实现前两者的beanNames
for (String ppName : postProcessorNames) {
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);
}
}
// 执行PriorityOrdered类的BeanFactoryPostProcessor
sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
invokeBeanFactoryPostProcessors(priorityOrderedPostProcessors, beanFactory);
// 执行Ordered类的BeanFactoryPostProcessor
List<BeanFactoryPostProcessor> orderedPostProcessors = new ArrayList<>();
for (String postProcessorName : orderedPostProcessorNames) {
orderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
}
sortPostProcessors(orderedPostProcessors, beanFactory);
invokeBeanFactoryPostProcessors(orderedPostProcessors, beanFactory);
// 执行其他所有没有执行过的BeanFactoryPostProcessor
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();
}
@Override
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) {
int registryId = System.identityHashCode(registry);
if (this.registriesPostProcessed.contains(registryId)) {
throw new IllegalStateException(
"postProcessBeanDefinitionRegistry already called on this post-processor against " + registry);
}
if (this.factoriesPostProcessed.contains(registryId)) {
throw new IllegalStateException(
"postProcessBeanFactory already called on this post-processor against " + registry);
}
this.registriesPostProcessed.add(registryId);
processConfigBeanDefinitions(registry);
}
最经典的案例就是mybatis的整合,通过了一个@MapperScan,即注入了一个MapperScannerConfigurer类,这个类继承自BeanDefinitionRegistryPostProcessor。
@Component
public class MyBeanFactoryPostProcessor implements BeanDefinitionRegistryPostProcessor {
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@interface Fallback{
String value();
}
@Override
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(registry);
scanner.addIncludeFilter(new AnnotationTypeFilter(Fallback.class));
int scan = scanner.scan("com.wugao.fallback");
}
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
//TODO 执行自己的逻辑
}
}
下一节我们将详细介绍ConfigurationClassPostProcessor的执行过程,这个类是产生BeanDifinition的关键。