public void refresh() throws BeansException, IllegalStateException {
synchronized (this.startupShutdownMonitor) {
prepareRefresh();//准备启动spring容器,设置容器的启动日期和活动标志
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();//获得容器ApplicationContext的子类BeanFactory。步骤如下:如果已经有了BeanFactory就销毁它里面的单例Bean并关闭这个BeanFactory。2.创建一个新的BeanFactory。3.对这个BeanFactory进行定制(customize),如allowBeanDefinitionOverriding,allowCircularReferences。4.转载BeanDefinitions(读取配置文件,将xml转换成对应得BeanDefinition)。5.检查是否同时启动了两个BeanFactory。
prepareBeanFactory(beanFactory);//配置BeanFactory(就是将ApplicationContext的一些属性配置到BeanFactory上吧)。这里做了很多事情,可以看看其源码,比较重要的如设置classLoader;将BeanPostProcess注册到BeanFactory里。
try {
// Allows post-processing of the bean factory in context subclasses.
postProcessBeanFactory(beanFactory);
invokeBeanFactoryPostProcessors(beanFactory);//触发BeanFactoryPostProcessors
registerBeanPostProcessors(beanFactory);//触发BeanPostProcessors
// 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();
finishBeanFactoryInitialization(beanFactory);//初始化单例的Bean,并将其保存起来。
// Last step: publish corresponding event.
finishRefresh();
}
catch (BeansException ex) {
// Destroy already created singletons to avoid dangling resources.
beanFactory.destroySingletons();
// Reset 'active' flag.
cancelRefresh(ex);
// Propagate exception to caller.
throw ex;
}
}
}