前言 最近打算花點時間好好看看spring的源碼,然而現在Spring的源碼經過迭代的版本太多了,比較龐大,看起來比較累,所以準備從最初的版本(interface21)開始入手,僅用於學習,理解其設計思想,後續慢慢研究其每次版本變更的內容。。。 先從interface21的一個典型web工程例子看起 ...
前言
最近打算花點時間好好看看spring的源碼,然而現在Spring的源碼經過迭代的版本太多了,比較龐大,看起來比較累,所以準備從最初的版本(interface21)開始入手,僅用於學習,理解其設計思想,後續慢慢研究其每次版本變更的內容。。。
先從interface21的一個典型web工程例子看起,寵物診所 - petclinic,因為該工程基本涵蓋了Spring的APO、IOC、JDBC、Web MVC、事務、國際化、主題切換、參數校驗等主要功能。。。
繼上一篇,瞭解完Log4jConfigListener(載入Log4j日誌)的流程後,看看ContextLoaderListener(載入Spring Web Application Context)流程是如何的~~~~~~~
對應的web.xml配置
<listener> <listener-class>com.interface21.web.context.ContextLoaderListener</listener-class> </listener>
執行時序圖(看不清的話可以點擊查看原圖)
時序圖中的各個步驟簡要分析
執行的入口在ContextLoaderListener類的contextInitialized方法,由於ContextLoaderListener類實現了ServletContextListener介面,所以在Servlet容器(tomcat)啟動時,會自動調用contextInitialized方法。
步驟描述:
- 進入ContextLoaderListener類的contextInitialized方法,該類只有一句代碼,執行ContextLoader.initContext(event.getServletContext())方法;
public void contextInitialized(ServletContextEvent event) { ContextLoader.initContext(event.getServletContext()); }
- 進入ContextLoader類的initContext方法,首先,從servletContext中獲取contextClass參數,如果配置了該參數,則創建該實例對象,否則創建預設的XmlWebApplicationContext實例對象,接下來調用XmlWebApplicationContext的setServletContext方法;
public static WebApplicationContext initContext(ServletContext servletContext) throws ApplicationContextException { servletContext.log("Loading root WebApplicationContext"); String contextClass = servletContext.getInitParameter(CONTEXT_CLASS_PARAM); // Now we must load the WebApplicationContext. // It configures itself: all we need to do is construct the class with a no-arg // constructor, and invoke setServletContext. try { Class clazz = (contextClass != null ? Class.forName(contextClass) : DEFAULT_CONTEXT_CLASS); logger.info("Loading root WebApplicationContext: using context class '" + clazz.getName() + "'"); if (!WebApplicationContext.class.isAssignableFrom(clazz)) { throw new ApplicationContextException("Context class is no WebApplicationContext: " + contextClass); } WebApplicationContext webApplicationContext = (WebApplicationContext) clazz.newInstance(); webApplicationContext.setServletContext(servletContext); return webApplicationContext; } catch (ApplicationContextException ex) { handleException("Failed to initialize application context", ex); } catch (BeansException ex) { handleException("Failed to initialize beans in application context", ex); } catch (ClassNotFoundException ex) { handleException("Failed to load config class '" + contextClass + "'", ex); } catch (InstantiationException ex) { handleException("Failed to instantiate config class '" + contextClass + "': does it have a public no arg constructor?", ex); } catch (IllegalAccessException ex) { handleException("Illegal access while finding or instantiating config class '" + contextClass + "': does it have a public no arg constructor?", ex); } catch (Throwable ex) { handleException("Unexpected error loading context configuration", ex); } return null; }
- 進入XmlWebApplicationContext類的setServletContext方法,首先,調用initConfigLocation方法從servletContext中獲取contextConfigLocation參數(Spring Application配置文件),如果沒配置該參數,則預設獲取/WEB-INF/applicationContext.xml該文件;
public void setServletContext(ServletContext servletContext) throws ApplicationContextException { this.servletContext = servletContext; this.configLocation = initConfigLocation(); logger.info("Using config location '" + this.configLocation + "'"); refresh(); if (this.namespace == null) { // We're the root context WebApplicationContextUtils.publishConfigObjects(this); // Expose as a ServletContext object WebApplicationContextUtils.publishWebApplicationContext(this); } }
- 迎來了非常關鍵的一步操作,調用AbstractApplicationContext類的refresh()方法,該方法具體如下,每個階段的英文註釋已經比較清晰了,下麵步驟也會做個詳細描述:
public final void refresh() throws ApplicationContextException { if (this.contextOptions != null && !this.contextOptions.isReloadable()) throw new ApplicationContextException("Forbidden to reload config"); this.startupTime = System.currentTimeMillis(); refreshBeanFactory(); if (getBeanDefinitionCount() == 0) logger.warn("No beans defined in ApplicationContext [" + getDisplayName() + "]"); else logger.info(getBeanDefinitionCount() + " beans defined in ApplicationContext [" + getDisplayName() + "]"); // invoke configurers that can override values in the bean definitions invokeContextConfigurers(); // load options bean for this context loadOptions(); // initialize message source for this context initMessageSource(); // initialize other special beans in specific context subclasses onRefresh(); // check for listener beans and register them refreshListeners(); // instantiate singletons this late to allow them to access the message source preInstantiateSingletons(); // last step: publish respective event publishEvent(new ContextRefreshedEvent(this)); }
- 首先,調用AbstractXmlApplicationContext類的refreshBeanFactory方法,該方法如下,具體完成的操作內容下麵步驟會詳細描述:
protected void refreshBeanFactory() throws ApplicationContextException { String identifier = "application context with display name [" + getDisplayName() + "]"; InputStream is = null; try { // Supports remote as well as local URLs is = getInputStreamForBeanFactory(); this.xmlBeanFactory = new XmlBeanFactory(getParent()); this.xmlBeanFactory.setEntityResolver(new ResourceBaseEntityResolver(this)); this.xmlBeanFactory.loadBeanDefinitions(is); if (logger.isInfoEnabled()) { logger.info("BeanFactory for application context: " + this.xmlBeanFactory); } } catch (IOException ex) { throw new ApplicationContextException("IOException parsing XML document for " + identifier, ex); } catch (NoSuchBeanDefinitionException ex) { throw new ApplicationContextException("Cannot load configuration: missing bean definition [" + ex.getBeanName() + "]", ex); } catch (BeansException ex) { throw new ApplicationContextException("Cannot load configuration: problem instantiating or initializing beans", ex); } finally { try { if (is != null) is.close(); } catch (IOException ex) { throw new ApplicationContextException("IOException closing stream for XML document for " + identifier, ex); } } }
- 調用XmlWebApplicationContext類的getInputStreamForBeanFactory方法,讀取階段3獲取到的配置文件為輸入流InputStream
protected InputStream getInputStreamForBeanFactory() throws IOException { InputStream in = getResourceAsStream(this.configLocation); if (in == null) { throw new FileNotFoundException("Config location not found: " + this.configLocation); } return in; }
- 返回配置文件輸入流InputStream
- 回到AbstractXmlApplicationContext的refreshBeanFactory方法,new出一個XmlBeanFactory對象
- 設置xmlBeanFactory.setEntityResolver,這裡的EntityResolver主要用於尋找DTD聲明
- 調用xmlBeanFactory的loadBeanDefinitions方法載入bean定義聲明
- 進入xmlBeanFactory類的loadBeanDefinitions方法,解析讀取的配置文件流InputStream為org.w3c.dom.Document對象,然後調用loadBeanDefinitions方法依次解析各個bean元素節點信息
public void loadBeanDefinitions(InputStream is) throws BeansException { if (is == null) throw new BeanDefinitionStoreException("InputStream cannot be null: expected an XML file", null); try { logger.info("Loading XmlBeanFactory from InputStream [" + is + "]"); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); logger.debug("Using JAXP implementation [" + factory + "]"); factory.setValidating(true); DocumentBuilder db = factory.newDocumentBuilder(); db.setErrorHandler(new BeansErrorHandler()); db.setEntityResolver(this.entityResolver != null ? this.entityResolver : new BeansDtdResolver()); Document doc = db.parse(is); loadBeanDefinitions(doc); } catch (ParserConfigurationException ex) { throw new BeanDefinitionStoreException("ParserConfiguration exception parsing XML", ex); } catch (SAXException ex) { throw new BeanDefinitionStoreException("XML document is invalid", ex); } catch (IOException ex) { throw new BeanDefinitionStoreException("IOException parsing XML document", ex); } finally { try { if (is != null) is.close(); } catch (IOException ex) { throw new FatalBeanException("IOException closing stream for XML document", ex); } } }
- 尋找Document中聲明為bean的Element節點,依次解析
public void loadBeanDefinitions(Document doc) throws BeansException { Element root = doc.getDocumentElement(); logger.debug("Loading bean definitions"); NodeList nl = root.getElementsByTagName(BEAN_ELEMENT); logger.debug("Found " + nl.getLength() + " <" + BEAN_ELEMENT + "> elements defining beans"); for (int i = 0; i < nl.getLength(); i++) { Node n = nl.item(i); loadBeanDefinition((Element) n); } }
- 解析Element節點內容,獲取class聲明信息、PropertyValues等信息,封裝成AbstractBeanDefinition對象,添加到beanDefinitionMap中
private void loadBeanDefinition(Element el) throws BeansException { // The DTD guarantees an id attribute is present String id = el.getAttribute(ID_ATTRIBUTE); logger.debug("Parsing bean definition with id '" + id + "'"); // Create BeanDefinition now: we'll build up PropertyValues later AbstractBeanDefinition beanDefinition; PropertyValues pvs = getPropertyValueSubElements(el); beanDefinition = parseBeanDefinition(el, id, pvs); registerBeanDefinition(id, beanDefinition); String name = el.getAttribute(NAME_ATTRIBUTE); if (name != null && !"".equals(name)) { // Automatically create this alias. Used for // names that aren't legal in id attributes registerAlias(id, name); } }
- 判斷是否需要註冊alias,放到aliasMap中,實際上就是維護了bean的name和id關係
- 返回到AbstractXmlApplicationContext類refreshBeanFactory方法中
- 返回到AbstractApplicationContext類refresh方法中
- 執行AbstractApplicationContext的invokeContextConfigurers方法,實際上內部是執行所有實現了BeanFactoryPostProcessor介面的bean的postProcessBeanFactory方法
private void invokeContextConfigurers() { String[] beanNames = getBeanDefinitionNames(BeanFactoryPostProcessor.class); for (int i = 0; i < beanNames.length; i++) { String beanName = beanNames[i]; BeanFactoryPostProcessor configurer = (BeanFactoryPostProcessor) getBean(beanName); configurer.postProcessBeanFactory(getBeanFactory()); } }
- 執行AbstractApplicationContext的loadOptions方法,獲取contextOptions bean,首先,查看配置文件是否已經配置contextOptions bean,沒有則自己創建一個new ContextOptions()對象,主要用於當應用運行時,是否可以重新載入該配置,如果配置成false的話,會在調用refresh方法時,拋出一個ApplicationContextException("Forbidden to reload config")異常;
private void loadOptions() { try { this.contextOptions = (ContextOptions) getBean(OPTIONS_BEAN_NAME); } catch (NoSuchBeanDefinitionException ex) { logger.info("No options bean (\"" + OPTIONS_BEAN_NAME + "\") found: using default"); this.contextOptions = new ContextOptions(); } }
- 執行AbstractApplicationContext的initMessageSource方法,獲取messageSource bean,首先,查看配置文件是否已經配置messageSource bean,沒有則自己創建一個StaticMessageSource對象,註意如果Parent context不為null的話,需要設置Parent MessageSource
private void initMessageSource() { try { this.messageSource = (MessageSource) getBean(MESSAGE_SOURCE_BEAN_NAME); // set parent message source if applicable, // and if the message source is defined in this context, not in a parent if (this.parent != null && (this.messageSource instanceof NestingMessageSource) && Arrays.asList(getBeanDefinitionNames()).contains(MESSAGE_SOURCE_BEAN_NAME)) { ((NestingMessageSource) this.messageSource).setParent(this.parent); } } catch (NoSuchBeanDefinitionException ex) { logger.info("No MessageSource found for [" + getDisplayName() + "]: using empty StaticMessageSource"); // use empty message source to be able to accept getMessage calls this.messageSource = new StaticMessageSource(); } }
- 執行AbstractXmlUiApplicationContext的onRefresh方法,獲取themeSource bean, 主題相關(如應用可配置暗色主題或亮色主題功能),同樣,這裡也首先查看配置文件是否已經配置themeSource bean,沒有則自己創建一個ResourceBundleThemeSource對象,註意這裡還需要根據判斷條件設置Parent ThemeSource
protected void onRefresh() { this.themeSource = UiApplicationContextUtils.initThemeSource(this); }
public static ThemeSource initThemeSource(ApplicationContext applicationContext) { ThemeSource themeSource; try { themeSource = (ThemeSource) applicationContext.getBean(THEME_SOURCE_BEAN_NAME); // set parent theme source if applicable, // and if the theme source is defined in this context, not in a parent if (applicationContext.getParent() instanceof ThemeSource && themeSource instanceof NestingThemeSource && Arrays.asList(applicationContext.getBeanDefinitionNames()).contains(THEME_SOURCE_BEAN_NAME)) { ((NestingThemeSource) themeSource).setParent((ThemeSource) applicationContext.getParent()); } } catch (NoSuchBeanDefinitionException ex) { logger.info("No ThemeSource found for [" + applicationContext.getDisplayName() + "]: using ResourceBundleThemeSource"); themeSource = new ResourceBundleThemeSource(); } return themeSource; }
- 執行AbstractApplicationContext的refreshListeners方法,尋找所有ApplicationListener bean,將其放到ApplicationEventMulticaster對象的Set集合中
private void refreshListeners() { logger.info("Refreshing listeners"); List listeners = BeanFactoryUtils.beansOfType(ApplicationListener.class, this); logger.debug("Found " + listeners.size() + " listeners in bean factory"); for (int i = 0; i < listeners.size(); i++) { ApplicationListener listener = (ApplicationListener) listeners.get(i); addListener(listener); logger.info("Bean listener added: [" + listener + "]"); } }
- 執行AbstractApplicationContext的preInstantiateSingletons方法,創建單例的bean實例,創建bean對象是在調用getBean方法時創建的,具體創建邏輯在getSharedInstance方法里;另外,對實現了ApplicationContextAware介面的bean,會調用對應的介面setApplicationContext方法,這裡涉及的細節比較多,後續有時間可以具體詳細分析;
private void preInstantiateSingletons() { logger.info("Configuring singleton beans in context"); String[] beanNames = getBeanDefinitionNames(); logger.debug("Found " + beanNames.length + " listeners in bean factory: names=[" + StringUtils.arrayToDelimitedString(beanNames, ",") + "]"); for (int i = 0; i < beanNames.length; i++) { String beanName = beanNames[i]; if (isSingleton(beanName)) { getBean(beanName); } } }
public Object getBean(String name) throws BeansException { Object bean = getBeanFactory().getBean(name); configureManagedObject(name, bean); return bean; }
private final synchronized Object getSharedInstance(String pname, Map newlyCreatedBeans) throws BeansException { // Get rid of the dereference prefix if there is one String name = transformedBeanName(pname); Object beanInstance = this.singletonCache.get(name); if (beanInstance == null) { logger.info("Creating shared instance of singleton bean '" + name + "'"); beanInstance = createBean(name, newlyCreatedBeans); this.singletonCache.put(name, beanInstance); } else { if (logger.isDebugEnabled()) logger.debug("Returning cached instance of singleton bean '" + name + "'"); } // Don't let calling code try to dereference the // bean factory if the bean isn't a factory if (isFactoryDereference(pname) && !(beanInstance instanceof FactoryBean)) { throw new BeanIsNotAFactoryException(name, beanInstance); } // Now we have the beanInstance, which may be a normal bean // or a FactoryBean. If it's a FactoryBean, we use it to // create a bean instance, unless the caller actually wants // a reference to the factory. if (beanInstance instanceof FactoryBean) { if (!isFactoryDereference(pname)) { // Configure and return new bean instance from factory FactoryBean factory = (FactoryBean) beanInstance; logger.debug("Bean with name '" + name + "' is a factory bean"); beanInstance = factory.getObject(); // Set pass-through properties if (factory.getPropertyValues() != null) { logger.debug("Applying pass-through properties to bean with name '" + name + "'"); new BeanWrapperImpl(beanInstance).setPropertyValues(factory.getPropertyValues()); } // Initialization is really up to factory //invokeInitializerIfNecessary(beanInstance); } else { // The user wants the factory itself logger.debug("Calling code asked for BeanFactory instance for name '" + name + "'"); } } // if we're dealing with a factory bean return beanInstance; }
private void configureManagedObject(String name, Object bean) { if (bean instanceof ApplicationContextAware && (!isSingleton(name) || !this.managedSingletons.contains(bean))) { logger.debug("Setting application context on ApplicationContextAware object [" + bean + "]"); ApplicationContextAware aca = (ApplicationContextAware) bean; aca.setApplicationContext(this); this.managedSingletons.add(bean); } }
- 執行AbstractApplicationContext的publishEvent方法,發佈ContextRefreshedEvent事件,如果parent不為空,一起發佈,內部的邏輯是執行對應eventListeners的onApplicationEvent方法
public final void publishEvent(ApplicationEvent event) { if (logger.isDebugEnabled()) { logger.debug("Publishing event in context [" + getDisplayName() + "]: " + event.toString()); } this.eventMulticaster.onApplicationEvent(event); if (this.parent != null) { parent.publishEvent(event); } }
- 回到XmlWebApplicationContext類
- 執行WebApplicationContextUtils.publishConfigObjects方法,尋找所有config bean,將其設置到ServletContext的屬性中
public static void publishConfigObjects(WebApplicationContext wac) throws ApplicationContextException { logger.info("Configuring config objects"); String[] beanNames = wac.getBeanDefinitionNames(); for (int i = 0; i < beanNames.length; i++) { String name = beanNames[i]; if (name.startsWith(CONFIG_OBJECT_PREFIX)) { // Strip prefix String strippedName = name.substring(CONFIG_OBJECT_PREFIX.length()); try { Object configObject = wac.getBean(name); wac.getServletContext().setAttribute(strippedName, configObject); logger.info("Config object with name [" + name + "] and class [" + configObject.getClass().getName() + "] initialized and added to ServletConfig"); } catch (BeansException ex) { throw new ApplicationContextException("Couldn't load config object with name '" + name + "': " + ex, ex); } } } }
- 執行WebApplicationContextUtils.publishWebApplicationContext,將WebApplicationContext設置到ServletContext屬性中
public static void publishWebApplicationContext(WebApplicationContext wac) { // Set WebApplicationContext as an attribute in the ServletContext so // other components in this web application can access it ServletContext sc = wac.getServletContext(); if (sc == null) throw new IllegalArgumentException("ServletContext can't be null in WebApplicationContext " + wac); sc.setAttribute(WebApplicationContext.WEB_APPLICATION_CONTEXT_ATTRIBUTE_NAME, wac); logger.info( "Loader initialized on server name " + wac.getServletContext().getServerInfo() + "; WebApplicationContext object is available in ServletContext with name '" + WebApplicationContext.WEB_APPLICATION_CONTEXT_ATTRIBUTE_NAME + "'"); }
- 返回webApplicationContext到ContextLoader類
- ContextLoaderListener.contextInitialized方法執行結束
就這樣,Spring Web Application Context載入完成了,是不是感覺也挺簡單的,主要就是讀取xml配置文件中bean的配置信息,創建bean實例放到一個map中維護,當然,中間還穿插了各種邏輯;
另外補充下,當Servlet容器銷毀時,會調用ContextLoaderListener的contextDestroyed方法,最終是調用ContextLoader.closeContext(event.getServletContext(),執行一些資源銷毀等操作,銷毀工廠創建的bean對象,發佈ContextClosedEvent事件等;
public void close() { logger.info("Closing application context [" + getDisplayName() + "]"); // destroy all cached singletons in this context, // invoking DisposableBean.destroy and/or "destroy-method" getBeanFactory().destroySingletons(); // publish respective event publishEvent(new ContextClosedEvent(this)); }
interface21代碼參考
https://github.com/peterchenhdu/interface21