1. 总体流程
- 创建设置
Environment和ResourceLoader(加载spring配置文件需要)
- 设置
spring 配置文件路径
- 处理
Environment 相关内容,包括调用和Environment有关的回调接口,判断required的环境变量
- 创建
beanFactory设置一些配置项,配置QualifierAnnotationAutowireCandidateResolver(不知道为什么不用InstantiationAwareBeanPostProcessor),加载BeanDefinition.
- 配置一些applicationContex特有的属性,包括
context's ClassLoader and post-processors.
- 调用扩展回调接口
postProcessBeanFactory,容许子类对BeanFactory做一些定制化配置
- 查找所有的
BeanFactoryPostProcessor并调用
- 查找并注册所有的
BeanPostProcessor.
- 查找名称为
messageSource,类型为MessageSource的bean,没有就创建,赋值给applicationContext的messageSource 成员变量
- 查找名称为
applicationEventMulticaster,类型为ApplicationEventMulticaster的bean,没有就创建,赋值给applicationContext的applicationEventMulticaster 成员变量
- 调用扩展接口
onRefresh。实际上springboot大部分都是通过监听器来实现扩展的,而不是子类扩展接口
- 将手动配置的
listener和配置资源里面的listener都加入ApplicationEventMulticaster
- 实例化所有单例非延迟创建的
bean
- 初始化生命周期管理器(LifecycleProcessor),调用所有实现
Lifecycle的bean的start方法,并发布ContextRefreshedEvent。
2. 代码解析
public ClassPathXmlApplicationContext(String[] configLocations, boolean refresh, ApplicationContext parent)
throws BeansException {
super(parent);
setConfigLocations(configLocations);
if (refresh) {
refresh();
}
}
public void refresh() throws BeansException, IllegalStateException {
synchronized (this.startupShutdownMonitor) {
prepareRefresh();
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
prepareBeanFactory(beanFactory);
try {
postProcessBeanFactory(beanFactory);
invokeBeanFactoryPostProcessors(beanFactory);
registerBeanPostProcessors(beanFactory);
initMessageSource();
initApplicationEventMulticaster();
onRefresh();
registerListeners();
finishBeanFactoryInitialization(beanFactory);
finishRefresh();
}
catch (BeansException ex) {
if (logger.isWarnEnabled()) {
logger.warn("Exception encountered during context initialization - " +
"cancelling refresh attempt: " + ex);
}
destroyBeans();
cancelRefresh(ex);
throw ex;
}
}
}
1. prepareRefresh
protected void prepareRefresh() {
this.startupDate = System.currentTimeMillis();
synchronized (this.activeMonitor) {
this.active = true;
}
if (logger.isInfoEnabled()) {
logger.info("Refreshing " + this);
}
initPropertySources();
getEnvironment().validateRequiredProperties();
}
2. 两个回调接口
- 在
beanFactory创建加载配置完成后的回调接口postProcessBeanFactory(beanFactory);
onfresh方法。