ApplicationContext Refresh流程
org.springframework.context.support.AbstractApplicationContext 的 refresh()方法。
按照 refresh()中的方法分为12个步骤,3个阶段。
-
阶段一:准备工作 阶段二:创建BeanFactory 阶段三:准备ApplicationContext
public void refresh() throws BeansException, IllegalStateException {
// 刷新和销毁的同步监视器
synchronized (this.startupShutdownMonitor) {
/**
阶段一:
* 1:创建 Envoriment 对象
* Envoriment:系统配置和自定义配置对象(jdk版本,xml,编码)
*/
prepareRefresh();
/**
阶段二:
* 2:创建 BeanFactory
*/
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
/**
阶段二:
* 3:注入特殊的对象
*/
prepareBeanFactory(beanFactory);
try {
/**
阶段二:
* 4:对 bean 工厂进行后置处理
*/
postProcessBeanFactory(beanFactory);
/**
阶段二:
* 5:调用在上下文中注册为 bean 的工厂处理器
*/
invokeBeanFactoryPostProcessors(beanFactory);
/**
阶段二:
* 6:注册拦截 bean 创建的 bean 处理器
*/
registerBeanPostProcessors(beanFactory);
/**
阶段三:
* 7:为 ApplicationContext 初始化 MessageSource
*/
initMessageSource();
/**
阶段三:
* 8:为 ApplicationContext 初始化事件多播器
*/
initApplicationEventMulticaster();
/**
阶段三:
* 9:初始化 ApplicationContext 中其它特殊的 bean
*/
onRefresh();
/**
阶段三:
* 10:检测并注册 监听器
*/
registerListeners();
/**
阶段三:
* 11:实例化所有的单例 Bean (非惰性化)
*/
finishBeanFactoryInitialization(beanFactory);
/**
阶段三:
* 12:完成 Application Refresh,调用 LifecycleProcessor 的 onRefresh() 方法并发布。
*/
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 Springs core, since we
// might not ever need metadata for singleton beans anymore...
resetCommonCaches();
}
}
}
