1. 程式人生 > >Spring原始碼閱讀--AbstractApplicationContext refresh()方法呼叫

Spring原始碼閱讀--AbstractApplicationContext refresh()方法呼叫

Spring初始化Ioc容器很重要的一個方法是由ApplicationContext子介面ConfigurableApplicationContext提供的refresh(),這個方法的作用是建立載入Spring容器配置(包括.xml配置,property檔案和資料庫模式等)。下面是各個refresh()呼叫的各個方法的作用解析:

@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.
			//主要是建立beanFactory,同時載入配置檔案.xml中的beanDefinition
			//通過String[] configLocations = getConfigLocations()獲取資源路徑,然後載入beanDefinition
			ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();

			// Prepare the bean factory for use in this context.
			//給beanFactory註冊一些標準組建,如ClassLoader,StandardEnvironment,BeanProcess
			prepareBeanFactory(beanFactory);

			try {
				// Allows post-processing of the bean factory in context subclasses.
				//提供給子類實現一些postProcess的註冊,如AbstractRefreshableWebApplicationContext註冊一些Servlet相關的
				//postProcess,真對web進行生命週期管理的Scope,通過registerResolvableDependency()方法註冊指定ServletRequest,HttpSession,WebRequest物件的工廠方法
				postProcessBeanFactory(beanFactory);

				// Invoke factory processors registered as beans in the context.
				//呼叫所有BeanFactoryProcessor的postProcessBeanFactory()方法
				invokeBeanFactoryPostProcessors(beanFactory);

				// Register bean processors that intercept bean creation.
				//註冊BeanPostProcessor,BeanPostProcessor作用是用於攔截Bean的建立
				registerBeanPostProcessors(beanFactory);

				// Initialize message source for this context.
				//初始化訊息Bean
				initMessageSource();

				// Initialize event multicaster for this context.
				//初始化上下文的事件多播組建,ApplicationEvent觸發時由multicaster通知給ApplicationListener
				initApplicationEventMulticaster();

				// Initialize other special beans in specific context subclasses.
				//ApplicationContext初始化一些特殊的bean
				onRefresh();

				// Check for listener beans and register them.
				//註冊事件監聽器,事件監聽Bean統一註冊到multicaster裡頭,ApplicationEvent事件觸發後會由multicaster廣播
				registerListeners();

				// Instantiate all remaining (non-lazy-init) singletons.
				//非延遲載入的單例Bean例項化
				finishBeanFactoryInitialization(beanFactory);

				// Last step: publish corresponding event.
				finishRefresh();
			}

			catch (BeansException ex) {
				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;
			}
		}
	}