publicvoidrefresh()throwsBeansException,IllegalStateException{synchronized(this.startupShutdownMonitor){// Prepare this context for refreshing.// 准备刷新,设置启动时间和属性,标记为活跃。prepareRefresh();// Tell the subclass to refresh the internal bean factory.//创建beanFactory,即Spring容器。并且解析xml,创建BeanDefinition,并且注册到Spring容器中// // 准备bean工厂:对bean工厂进行配置,如设置类加载器、设置bean的表达式解析器、注册后置处理器等。// //加载bean定义:根据配置文件(如XML文件)或注解加载bean定义。这一步将解析配置文件,将bean定义注册到bean工厂中。ConfigurableListableBeanFactory beanFactory =obtainFreshBeanFactory();//进一步配置bean工厂,注册一些需要的处理器,设置bean的作用域和自动装配规则。prepareBeanFactory(beanFactory);try{// 允许在bean工厂创建之后,bean定义资源加载之前,注册或修改bean定义。postProcessBeanFactory(beanFactory);// 调用所有注册的bean工厂后处理器。invokeBeanFactoryPostProcessors(beanFactory);//注册bean后处理器,用于扩展bean的创建过程。registerBeanPostProcessors(beanFactory);// 初始化消息源,用于国际化。initMessageSource();// 初始化应用事件多播器,用于发布事件。initApplicationEventMulticaster();// 空方法,继承类可以重写此方法进行自定义操作。onRefresh();// 注册监听器,将监听器注册到多播器。registerListeners();// 完成bean工厂的初始化,实例化所有非懒加载的单例。finishBeanFactoryInitialization(beanFactory);// 完成容器的刷新,通知监听器容器已准备就绪,开始发布应用上下文准备就绪事件。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();}}}