Spring容器中最核心的方法就是refresh方法,现在我们就一起探究下这个refresh方法的内部原理吧。
refresh的基础实现是在核心类AbstractApplicionContext中,代码和简单解释如下:
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();
}
}
}
接下来会对每个子方法做详细的介绍:
1. prepareRefresh()
- 容器状态设置
- 初始化属性设置
- 检查必备属性是否存在
2. obtainFreshBeanFactory()
通知子类刷新内部的beanFactory,主要作用是创建beanFactory与加载BeanDefinition
Spring进阶- Spring IOC实现原理详解之IOC初始化流程 | Java 全栈知识体系 (pdai.tech)
3. prepareBeanFactory(beanFactory)
beanFactory初始化
4. postProcessBeanFactory(beanFactory)
子类中对beanFactory的初始化
5. invokeBeanFactoryPostProcessors(beanFactory)
执行BeanFactoryPostProcessor和BeanDefinitionRegistryPostProcessor两种后置处理器,主要作用是在bean实例化之前,对beanDefinition进行自定义的调整和修改。
详解
该方法内部的主要逻辑是将两种类型的后置处理器分类、排序、然后执行。
有一个重要的后置处理器ConfigurationClassPostProcessor,主要用来处理配置类,加载相关的BeanDefinition。
6. registerBeanPostProcessors(beanFactory)
注册bean后置处理器
7. initMessageSource()
初始化国际化信息设置
8. initApplicationEventMulticaster()
初始化该容器的事件广播器
9. onRefresh()
在子类中对特定的类进行特定的refresh处理
10. registerListeners()
注册监听器
11. finishBeanFactoryInitialization(beanFactory)
完成bean的初始化,该方法是refresh()的核心方法
12. finishRefresh()
完成refresh()方法