Spring原始碼閱讀——ApplicationContext
阿新 • • 發佈:2018-11-11
Spring中提供了一個介面ApplicationContext,用於擴充套件BeanFactory中現有的功能。它提供了更多的功能。現在我們來看下它的實現:
public ClassPathXmlApplicationContext(String[] configLocations, boolean refresh, ApplicationContext parent) throws BeansException { super(parent); setConfigLocations(configLocations); if (refresh) { refresh(); } }
其中refresh();方法幾乎包含了所有的功能,邏輯非常清晰
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 ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory(); // Prepare the bean factory for use in this context. //對BeanFactory進行各種功能填充 prepareBeanFactory(beanFactory); try { // Allows post-processing of the bean factory in context subclasses. //子類覆蓋方法做額外處理 postProcessBeanFactory(beanFactory); // Invoke factory processors registered as beans in the context. //啟用各種BeanFactory處理器 invokeBeanFactoryPostProcessors(beanFactory); // Register bean processors that intercept bean creation. //註冊攔截Bean建立的Bean處理器,這裡只是註冊,真正地呼叫在getBean的時候,比如配置檔案通過${}讀取等 registerBeanPostProcessors(beanFactory); // Initialize message source for this context. //為上下文初始化Message源,(比如國際化處理) initMessageSource(); // Initialize event multicaster for this context. //初始化應用訊息廣播,並放入 applicationEventMulticaster bean中 initApplicationEventMulticaster(); // Initialize other special beans in specific context subclasses. //留給子類來初始化其它的bean onRefresh(); // Check for listener beans and register them. //在所有註冊的bean中查詢Listener bean,註冊到訊息廣播器中 registerListeners(); // Instantiate all remaining (non-lazy-init) singletons. //初始化剩下的單例項 finishBeanFactoryInitialization(beanFactory); //完成重新整理過程,通知生命週期護處理器lifecycleProcessor重新整理過程,同時發出ContextRefreshEvent通知別人(LifecycleProcessor 用來與所有宣告的bean的週期做狀態更新) // 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(); } } }