一、前言
上一篇文章Spring源码解析-IOC容器启动流程(一),前四步已经分析了容器的准备工作和BeanFactory的创建和预处理操作,这篇文章主要解析的是后几步的操作。
阅读本文建议提前了解Bean的生命周期,观察者模式,监听器的使用。
常用英译汉介绍:
英文 | 中文 |
---|---|
Source | 资源 |
Annotation | 注解 |
Refresh | 刷新 |
Post | 后置的 |
Processor | 处理器 |
Init(initialize) | 初始化 |
Invoke | 执行 |
Regist | 注册 |
Multicaster | 多路广播 |
了解这些常见的词汇后,看到类名、方法名和源码上的注释就可以大体猜出来干什么用的,这对阅读源码帮助很大。
二、核心refresh()方法源码
/*AbstractApplicationContext.class*/
@Override
public void refresh() throws BeansException, IllegalStateException {
synchronized (this.startupShutdownMonitor) {
// Prepare this context for refreshing.
prepareRefresh();
// Tell the subclass to refresh the internal bean factory.
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
// Prepare the bean factory for use in this context.
prepareBeanFactory(beanFactory);
try {
// Allows post-processing of the bean factory in context subclasses.
postProcessBeanFactory(beanFactory);
// Invoke factory processors registered as beans in the context.
invokeBeanFactoryPostProcessors(beanFactory);
// Register bean processors that intercept bean creation.
registerBeanPostProcessors(beanFactory);
// Initialize message source for this context.
initMessageSource();
// Initialize event multicaster for this context.
initApplicationEventMulticaster();
// Initialize other special beans in specific context subclasses.
onRefresh();
// Check for listener beans and register them.
registerListeners();
// Instantiate all remaining (non-lazy-init) singletons.
finishBeanFactoryInitialization(beanFactory);
// Last step: publish corresponding event.
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();
}
}
}
三、refresh()流程解析
5.invokeBeanFactoryPostProcessors(beanFactory);
直接翻译得,执行BeanFactory后置处理(执行BeanFactoryPostProcessors中实现的方法)。为什么现在能执行BeanFactory的后置处理器?因为BeanFactory已经
完全了初始化了。
到这里我终于碰到了一个我接触过的类了,这是我在研究bean生命周期方法执行顺序时使用过的一个接口,里面实现的方法能在BeanFactory初始化之后执行,终于算搭上勾了,不知道各位读者是什么感受?。
既然提到了BeanFactoryPostProcessors接口,那就有必要再介绍一个有关的接口了。
补充: BeanDefinitionRegistryPostProcessor
BeanDefinitionRegistryPostProcessor继承自BeanFactoryPostProcessor,是BeanFactoryPostProcessor的子接口。
spring官方解释是:允许在正常的BeanFactoryPostProcessor检测开始之前注册更多的自定义bean。如果自己实现了这个接口,就可以在BeanFactory后置处理器操作之前,自定义的注册bean,例子如下。
public class MyBeanFactoryRegistry implements BeanDefinitionRegistryPostProcessor {
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
}
@Override
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
RootBeanDefinition dog= new RootBeanDefinition(Dog.class);
// 注册一个名为dog的bean
registry.registerBeanDefinition("dog", dog);
}
}
这样的话,容器中就多了一个id为dog的bean。
说完了这两个后置处理器,接下来进入invokeBeanFactoryPostProcessors方法:
protected void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory) {
PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(beanFactory, getBeanFactoryPostProcessors());
// Detect a LoadTimeWeaver and prepare for weaving, if found in the meantime
// (e.g. through an @Bean method registered by ConfigurationClassPostProcessor)
if (beanFactory.getTempClassLoader() == null && beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
}
}
第一句invokeBeanFactoryPostProcessors(beanFactory, getBeanFactoryPostProcessors())就是我们要分析的重点,直译就是“执行BeanFactory后置处理器方法”,这个方法的两个参数,第一个就是要被增强的BeanFactory,第二个就是所有的BeanFactoryPostProcessor的方法集,类型是List<BeanFactoryPostProcessor>,进入方法(方法比较长,不要一句一句读,看我写的注释,分模块读):
public static void invokeBeanFactoryPostProcessors(
ConfigurableListableBeanFactory beanFactory, List<BeanFactoryPostProcessor> beanFactoryPostProcessors) {
Set<String> processedBeans = new HashSet<String>();
if (beanFactory instanceof BeanDefinitionRegistry) {
BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
List