@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.
//核心:告诉要使用当前模板的子类自己去初始化DefaultListableBeanFactory工厂。
//如果当前模板上下文持有DefaultListableBeanFactory工厂,
//那么就销毁当前bean并且关闭该工厂。
//如果当前模板上下文没有持有DefaultListableBeanFactory工厂,
//那么就创建当前DefaultListableBeanFactory工厂并且加载Bean的配置信息
//创建DefaultListableBeanFactory工厂过程:
//如果当前工厂持有的上下文是ConfigurableApplicationContext的实现,
//那么就使用ConfigurableApplicationContext的父类工厂,
//如果不是直接使用ApplicationContext(ApplicationContext其实就是BeanFactory)。
//细节:https://blog.csdn.net/yp1125/article/details/79928188
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
// Prepare the bean factory for use in this context.
//向ConfigurableListableBeanFactory添加组件
//1、设置 classLoader
//2、设置 bean 表达式解析器
//3、添加一个 BeanPostProcessor【ApplicationContextAwareProcessor】
//4、设置忽略自动装配的接口,即不能通过注解自动注入
//5、注册可以解析的自动装配类,即可以在任意组件中通过注解自动注入
//6、添加一个 BeanPostProcessor【ApplicationListenerDetector】
//7、添加编译时的 AspectJ
//8、注册 environment 组件,类型是【ConfigurableEnvironment】
//9、注册 systemProperties 组件,类型是【Map
//10、注册 systemEnvironment 组件,类型是【Map
prepareBeanFactory(beanFactory);
try {
// Allows post-processing of the bean factory in context subclasses.
postProcessBeanFactory(beanFactory);
// Invoke factory processors registered as beans in the context.
invokeBeanFactoryPostProcessors(beanFactory);
// Register bean processors that intercept bean creation.
registerBeanPostProcessors(beanFactory);
// Initialize message source for this context.
initMessageSource();
// Initialize event multicaster for this context.
initApplicationEventMulticaster();
// Initialize other special beans in specific context subclasses.
onRefresh();
// Check for listener beans and register them.
registerListeners();
// Instantiate all remaining (non-lazy-init) singletons.
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();
}
}
}