看下面的代码注释
@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. 告诉子类刷新内部bean工厂
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
// Prepare the bean factory for use in this context. 准备bean工厂
prepareBeanFactory(beanFactory);
try {
// Allows post-processing of the bean factory in context subclasses. 允许在上下文子类中对bean工厂进行后处理。
postProcessBeanFactory(beanFactory);
// Invoke factory processors registered as beans in the context. 设定bean工厂处理器
invokeBeanFactoryPostProcessors(beanFactory);
// Register bean processors that intercept bean creation. 注册bean处理拦截器
registerBeanPostProcessors(beanFactory);
// Initialize message source for this context.
// 初始化消息源
initMessageSource();
// Initialize event multicaster for this context. 初始化事件广播器
initApplicationEventMulticaster();
// Initialize other special beans in specific context subclasses. 初始化一下特殊bean
onRefresh();
// Check for listener beans and register them. 注册监听实例
registerListeners();
// Instantiate all remaining (non-lazy-init) singletons. 实例化所有剩余的(非lazy init)单例
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();
}
}
}
总结
简要来说分为下面几个步骤:
- 刷新预处理
- 解析配置信息 注册BeanFactory
- 设置bean 类加载器
- bean加载前后自定义想做的事
- 初始化事件广播器
- 初始化所有bean
- 广播applicationcontext初始化完成