public void refresh() throws BeansException, IllegalStateException {
synchronized (this.startupShutdownMonitor) {
// Prepare this context for refreshing.
prepareRefresh();
// 从GenericApplicationContext中获取
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
// 1)设置忽略Aware相关的依赖 (beanFactory.ignoreDependencyInterface)
// 2) 注册已知的依赖 (beanFactory.registerResolvableDependency)
// BeanFactory、ResourceLoader、ApplicationEventPublisher、ApplicationContext
// 3)注册BeanPostProcessor (beanFactory.addBeanPostProcessor)
// ApplicationContextAwareProcessor
// ApplicationListenerDetector
// 4)注册环境相关的bean (beanFactory.registerSingleton)
// environment、systemProperties、systemEnvironment
prepareBeanFactory(beanFactory)
try {
// 空方法
postProcessBeanFactory(beanFactory);
// bean注册的核心逻辑
// 一、处理BeanDefinitionRegistryPostProcessor
// 1. 调用早期注册的BeanDefinitionRegistryPostProcessor.postProcessBeanDefinitionRegistry(initialize阶段注册的)
// 2. 从已经注册的beanDefinition中找出实现BeanDefinitionRegistryPostProcessor接口的beanDefinition,
// 实例化并调用postProcessBeanDefinitionRegistry
// 1) 处理实现PriorityOrdered接口的
// 2) 处理实现Ordered接口的
// 3) 处理剩余的,循环处理,直到找不到新的BeanDefinitionRegistryPostProcessor
// 3. 调用所有BeanDefinitionRegistryPostProcessor.postProcessBeanFactory方法
// 4. 调用早期注册的BeanFactoryPostProcessor.postProcessBeanFactory方法
//
// 二、处理BeanFactoryPostProcessor
// 1. 从已经注册的beanDefinition中找出实现BeanFactoryPostProcessor接口的beanDefinition,
// 实例化并调用postProcessBeanFactory方法
// 1) 处理实现PriorityOrdered接口的
// 2) 处理实现Ordered接口的
// 3) 处理剩余的
invokeBeanFactoryPostProcessors(beanFactory);
// 注册BeanPostProcessor
// 从已经注册的beanDefinition中找出实现BeanPostProcessor接口的beanDefinition
// 按照不同的优先级,实例化这些BeanPostProcessor
// 并调用beanFactory.addBeanPostProcessor进行注册
registerBeanPostProcessors(beanFactory);
// 初始化MessageSource,调用beanFactory.registerSingleton进行注册
initMessageSource();
// 实例化ApplicationEventMulticaster,beanFactory.registerSingleton进行注册
initApplicationEventMulticaster();
// 空方法
onRefresh();
// 注册ApplicationListener到ApplicationEventMulticaster
// 1)先注册已经指定的ApplicationListener
// 2)从已经注册的beanDefinition中找出实现ApplicationListener接口的bean名称并注册
// 3)广播指定的ApplicationEvent
registerListeners();
// 实例化所有非lazy的单例
// 循环所有注册的beanDefinition,判断如果是单例且非lazy,调用getBean进行实例化
// 如果单例bean实现SmartInitializingSingleton接口,调用该接口的afterSingletonsInstantiated方法,用来做初始化
finishBeanFactoryInitialization(beanFactory);
// 广播ContextRefreshedEvent事件
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();
}
}
}