看下面的代碼注釋
@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初始化完成