你要知道的SpringMVC啟動流程和源碼分析都在這里
轉(zhuǎn)載請注明出處 http://www.lxweimin.com/p/dc64d02e49ac
本系列文章主要根據(jù)源碼講解SpringMVC
的啟動過程,以及相關(guān)重要組件的源碼分析。閱讀此系列文章需要具備Spring
以及SpringMVC
相關(guān)知識。本文將分以下幾篇文章進(jìn)行講解,讀者可按需查閱。
- SpringMVC 啟動流程及相關(guān)源碼分析
- SpringMVC DispatcherServlet執(zhí)行流程及源碼分析
- SpringMVC HandlerMapping源碼分析
- SpringMVC HandlerAdapter源碼分析
SpringMVC 啟動流程及相關(guān)源碼分析
熟悉SpringMVC
的啟動過程,有助于我們理解相關(guān)文件配置的原理,深入理解SpringMVC
的設(shè)計原理和執(zhí)行過程。
Web應(yīng)用部署初始化過程 (Web Application Deployement)
參考Oracle
官方文檔Java Servlet Specification,可知Web應(yīng)用部署的相關(guān)步驟如下:
當(dāng)一個Web應(yīng)用部署到容器內(nèi)時(eg.tomcat),在Web應(yīng)用開始響應(yīng)執(zhí)行用戶請求前,以下步驟會被依次執(zhí)行:
- 部署描述文件中(eg.tomcat的web.xml)由
<listener>
元素標(biāo)記的事件監(jiān)聽器會被創(chuàng)建和初始化 - 對于所有事件監(jiān)聽器,如果實現(xiàn)了
ServletContextListener
接口,將會執(zhí)行其實現(xiàn)的contextInitialized()
方法 - 部署描述文件中由
<filter>
元素標(biāo)記的過濾器會被創(chuàng)建和初始化,并調(diào)用其init()
方法 - 部署描述文件中由
<servlet>
元素標(biāo)記的servlet會根據(jù)<load-on-startup>
的權(quán)值按順序創(chuàng)建和初始化,并調(diào)用其init()
方法
通過上述官方文檔的描述,可繪制如下Web應(yīng)用部署初始化
流程執(zhí)行圖。
可以發(fā)現(xiàn),在tomcat
下web應(yīng)用
的初始化流程是,先初始化listener
接著初始化filter
最后初始化servlet
,當(dāng)我們清楚認(rèn)識到Web應(yīng)用
部署到容器后的初始化過程后,就可以進(jìn)一步深入探討SpringMVC
的啟動過程。
Spring MVC啟動過程
接下來以一個常見的簡單web.xml
配置進(jìn)行Spring MVC
啟動過程的分析,web.xml
配置內(nèi)容如下:
<web-app>
<display-name>Web Application</display-name>
<!--全局變量配置-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext-*.xml</param-value>
</context-param>
<!--監(jiān)聽器-->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!--解決亂碼問題的filter-->
<filter>
<filter-name>CharacterEncodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>utf-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!--Restful前端控制器-->
<servlet>
<servlet-name>springMVC_rest</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-mvc.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>springMVC_rest</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
Listener的初始化過程
首先定義了<context-param>
標(biāo)簽,用于配置一個全局變量,<context-param>
標(biāo)簽的內(nèi)容讀取后會被放進(jìn)application
中,做為Web應(yīng)用的全局變量使用,接下來創(chuàng)建listener
時會使用到這個全局變量,因此,Web應(yīng)用在容器中部署后,進(jìn)行初始化時會先讀取這個全局變量,之后再進(jìn)行上述講解的初始化啟動過程。
接著定義了一個ContextLoaderListener類
的listener
。查看ContextLoaderListener
的類聲明源碼如下圖:
ContextLoaderListener
類繼承了ContextLoader
類并實現(xiàn)了ServletContextListener
接口,首先看一下前面講述的ServletContextListener
接口源碼:
該接口只有兩個方法contextInitialized
和contextDestroyed
,這里采用的是觀察者模式,也稱為為訂閱-發(fā)布模式,實現(xiàn)了該接口的listener
會向發(fā)布者進(jìn)行訂閱,當(dāng)Web應(yīng)用
初始化或銷毀時會分別調(diào)用上述兩個方法。
繼續(xù)看ContextLoaderListener
,該listener
實現(xiàn)了ServletContextListener
接口,因此在Web應(yīng)用
初始化時會調(diào)用該方法,該方法的具體實現(xiàn)如下:
/**
* Initialize the root web application context.
*/
@Override
public void contextInitialized(ServletContextEvent event) {
initWebApplicationContext(event.getServletContext());
}
ContextLoaderListener
的contextInitialized()
方法直接調(diào)用了initWebApplicationContext()
方法,這個方法是繼承自ContextLoader類
,通過函數(shù)名可以知道,該方法是用于初始化Web應(yīng)用上下文,即IoC容器
,這里使用的是代理模式,繼續(xù)查看ContextLoader類
的initWebApplicationContext()
方法的源碼如下:
/**
* Initialize Spring's web application context for the given servlet context,
* using the application context provided at construction time, or creating a new one
* according to the "{@link #CONTEXT_CLASS_PARAM contextClass}" and
* "{@link #CONFIG_LOCATION_PARAM contextConfigLocation}" context-params.
* @param servletContext current servlet context
* @return the new WebApplicationContext
* @see #ContextLoader(WebApplicationContext)
* @see #CONTEXT_CLASS_PARAM
* @see #CONFIG_LOCATION_PARAM
*/
//servletContext,servlet上下文,即application對象
public WebApplicationContext initWebApplicationContext(ServletContext servletContext) {
/*
首先通過WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE
這個String類型的靜態(tài)變量獲取一個根IoC容器,根IoC容器作為全局變量
存儲在application對象中,如果存在則有且只能有一個
如果在初始化根WebApplicationContext即根IoC容器時發(fā)現(xiàn)已經(jīng)存在
則直接拋出異常,因此web.xml中只允許存在一個ContextLoader類或其子類的對象
*/
if (servletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE) != null) {
throw new IllegalStateException(
"Cannot initialize context because there is already a root application context present - " +
"check whether you have multiple ContextLoader* definitions in your web.xml!");
}
Log logger = LogFactory.getLog(ContextLoader.class);
servletContext.log("Initializing Spring root WebApplicationContext");
if (logger.isInfoEnabled()) {
logger.info("Root WebApplicationContext: initialization started");
}
long startTime = System.currentTimeMillis();
try {
// Store context in local instance variable, to guarantee that
// it is available on ServletContext shutdown.
// 如果當(dāng)前成員變量中不存在WebApplicationContext則創(chuàng)建一個根WebApplicationContext
if (this.context == null) {
this.context = createWebApplicationContext(servletContext);
}
if (this.context instanceof ConfigurableWebApplicationContext) {
ConfigurableWebApplicationContext cwac = (ConfigurableWebApplicationContext) this.context;
if (!cwac.isActive()) {
// The context has not yet been refreshed -> provide services such as
// setting the parent context, setting the application context id, etc
if (cwac.getParent() == null) {
// The context instance was injected without an explicit parent ->
// determine parent for root web application context, if any.
//為根WebApplicationContext設(shè)置一個父容器
ApplicationContext parent = loadParentContext(servletContext);
cwac.setParent(parent);
}
//配置并刷新整個根IoC容器,在這里會進(jìn)行Bean的創(chuàng)建和初始化
configureAndRefreshWebApplicationContext(cwac, servletContext);
}
}
/*
將創(chuàng)建好的IoC容器放入到application對象中,并設(shè)置key為WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE
因此,在SpringMVC開發(fā)中可以在jsp中通過該key在application對象中獲取到根IoC容器,進(jìn)而獲取到相應(yīng)的Ben
*/
servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, this.context);
ClassLoader ccl = Thread.currentThread().getContextClassLoader();
if (ccl == ContextLoader.class.getClassLoader()) {
currentContext = this.context;
}
else if (ccl != null) {
currentContextPerThread.put(ccl, this.context);
}
if (logger.isDebugEnabled()) {
logger.debug("Published root WebApplicationContext as ServletContext attribute with name [" +
WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE + "]");
}
if (logger.isInfoEnabled()) {
long elapsedTime = System.currentTimeMillis() - startTime;
logger.info("Root WebApplicationContext: initialization completed in " + elapsedTime + " ms");
}
return this.context;
}
catch (RuntimeException ex) {
logger.error("Context initialization failed", ex);
servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, ex);
throw ex;
}
catch (Error err) {
logger.error("Context initialization failed", err);
servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, err);
throw err;
}
}
initWebApplicationContext()
方法如上注解講述,主要目的就是創(chuàng)建root WebApplicationContext對象
即根IoC容器
,其中比較重要的就是,整個Web應(yīng)用
如果存在根IoC容器
則有且只能有一個,根IoC容器
作為全局變量存儲在ServletContext
即application對象
中。將根IoC容器
放入到application對象
之前進(jìn)行了IoC容器
的配置和刷新操作,調(diào)用了configureAndRefreshWebApplicationContext()
方法,該方法源碼如下:
protected void configureAndRefreshWebApplicationContext(ConfigurableWebApplicationContext wac, ServletContext sc) {
if (ObjectUtils.identityToString(wac).equals(wac.getId())) {
// The application context id is still set to its original default value
// -> assign a more useful id based on available information
String idParam = sc.getInitParameter(CONTEXT_ID_PARAM);
if (idParam != null) {
wac.setId(idParam);
}
else {
// Generate default id...
wac.setId(ConfigurableWebApplicationContext.APPLICATION_CONTEXT_ID_PREFIX +
ObjectUtils.getDisplayString(sc.getContextPath()));
}
}
wac.setServletContext(sc);
/*
CONFIG_LOCATION_PARAM = "contextConfigLocation"
獲取web.xml中<context-param>標(biāo)簽配置的全局變量,其中key為CONFIG_LOCATION_PARAM
也就是我們配置的相應(yīng)Bean的xml文件名,并將其放入到WebApplicationContext中
*/
String configLocationParam = sc.getInitParameter(CONFIG_LOCATION_PARAM);
if (configLocationParam != null) {
wac.setConfigLocation(configLocationParam);
}
// The wac environment's #initPropertySources will be called in any case when the context
// is refreshed; do it eagerly here to ensure servlet property sources are in place for
// use in any post-processing or initialization that occurs below prior to #refresh
ConfigurableEnvironment env = wac.getEnvironment();
if (env instanceof ConfigurableWebEnvironment) {
((ConfigurableWebEnvironment) env).initPropertySources(sc, null);
}
customizeContext(sc, wac);
wac.refresh();
}
比較重要的就是獲取到了web.xml
中的<context-param>標(biāo)簽
配置的全局變量contextConfigLocation
,并最后一行調(diào)用了refresh()
方法,ConfigurableWebApplicationContext
是一個接口,通過對常用實現(xiàn)類ClassPathXmlApplicationContext
逐層查找后可以找到一個抽象類AbstractApplicationContext
實現(xiàn)了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.
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
// Prepare the bean factory for use in this context.
prepareBeanFactory(beanFactory);
try {
// Allows post-processing of the bean factory in context subclasses.
postProcessBeanFactory(beanFactory);
// Invoke factory processors registered as beans in the context.
invokeBeanFactoryPostProcessors(beanFactory);
// Register bean processors that intercept bean creation.
registerBeanPostProcessors(beanFactory);
// 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();
// Instantiate all remaining (non-lazy-init) singletons.
finishBeanFactoryInitialization(beanFactory);
// 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();
}
}
}
該方法主要用于創(chuàng)建并初始化contextConfigLocation類
配置的xml文件
中的Bean
,因此,如果我們在配置Bean
時出錯,在Web應(yīng)用
啟動時就會拋出異常,而不是等到運行時才拋出異常。
整個ContextLoaderListener類
的啟動過程到此就結(jié)束了,可以發(fā)現(xiàn),創(chuàng)建ContextLoaderListener
是比較核心的一個步驟,主要工作就是為了創(chuàng)建根IoC容器
并使用特定的key
將其放入到application
對象中,供整個Web應(yīng)用
使用,由于在ContextLoaderListener類
中構(gòu)造的根IoC容器
配置的Bean
是全局共享的,因此,在<context-param>
標(biāo)識的contextConfigLocation
的xml配置文件
一般包括:數(shù)據(jù)庫DataSource
、DAO層
、Service層
、事務(wù)
等相關(guān)Bean
。
在JSP
中可以通過以下兩種方法獲取到根IoC容器
從而獲取相應(yīng)Bean
:
WebApplicationContext applicationContext = (WebApplicationContext) application.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
WebApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContext(getServletContext());
Filter的初始化
在監(jiān)聽器listener
初始化完成后,按照文章開始的講解,接下來會進(jìn)行filter
的初始化操作,filter
的創(chuàng)建和初始化中沒有涉及IoC容器
的相關(guān)操作,因此不是本文講解的重點,本文舉例的filter
是一個用于編碼用戶請求和響應(yīng)的過濾器,采用utf-8
編碼用于適配中文。
Servlet的初始化
Web應(yīng)用
啟動的最后一個步驟就是創(chuàng)建和初始化相關(guān)Servlet
,在開發(fā)中常用的Servlet
就是DispatcherServlet類
前端控制器,前端控制器作為中央控制器是整個Web應(yīng)用
的核心,用于獲取分發(fā)用戶請求并返回響應(yīng),借用網(wǎng)上一張關(guān)于DispatcherServlet類
的類圖,其類圖如下所示:
通過類圖可以看出DispatcherServlet類
的間接父類實現(xiàn)了Servlet接口
,因此其本質(zhì)上依舊是一個Servlet
。DispatcherServlet類
的設(shè)計很巧妙,上層父類不同程度的實現(xiàn)了相關(guān)接口的部分方法,并留出了相關(guān)方法用于子類覆蓋,將不變的部分統(tǒng)一實現(xiàn),將變化的部分預(yù)留方法用于子類實現(xiàn),本文關(guān)注的是DispatcherServelt類
的初始化過程,沒有深入探討其如何對用戶請求做出響應(yīng),讀者有興趣可以閱讀本系列文章的第二篇SpringMVC DispatcherServlet源碼分析。
通過對上述類圖中相關(guān)類的源碼分析可以繪制如下相關(guān)初始化方法調(diào)用邏輯:
通過類圖和相關(guān)初始化函數(shù)調(diào)用的邏輯來看,DispatcherServlet類
的初始化過程將模板方法使用的淋漓盡致,其父類完成不同的統(tǒng)一的工作,并預(yù)留出相關(guān)方法用于子類覆蓋去完成不同的可變工作。
DispatcherServelt
類的本質(zhì)是Servlet
,通過文章開始的講解可知,在Web應(yīng)用
部署到容器后進(jìn)行Servlet
初始化時會調(diào)用相關(guān)的init(ServletConfig)
方法,因此,DispatchServlet類
的初始化過程也由該方法開始。上述調(diào)用邏輯中比較重要的就是FrameworkServlet抽象類
中的initServletBean()
方法、initWebApplicationContext()
方法以及DispatcherServlet類
中的onRefresh()
方法,接下來會逐一進(jìn)行講解。
首先查看一下initServletBean()
的相關(guān)源碼如下圖所示:
該方法是重寫了FrameworkServlet抽象類
父類HttpServletBean抽象類
的initServletBean()
方法,HttpServletBean抽象類
在執(zhí)行init()
方法時會調(diào)用initServletBean()
方法,由于多態(tài)的特性,最終會調(diào)用其子類FrameworkServlet抽象類
的initServletBean()
方法。該方法由final
標(biāo)識,子類就不可再次重寫了。該方法中比較重要的就是initWebApplicationContext()
方法的調(diào)用,該方法仍由FrameworkServlet抽象類
實現(xiàn),繼續(xù)查看其源碼如下所示:
/**
* Initialize and publish the WebApplicationContext for this servlet.
* <p>Delegates to {@link #createWebApplicationContext} for actual creation
* of the context. Can be overridden in subclasses.
* @return the WebApplicationContext instance
* @see #FrameworkServlet(WebApplicationContext)
* @see #setContextClass
* @see #setContextConfigLocation
*/
protected WebApplicationContext initWebApplicationContext() {
/*
獲取由ContextLoaderListener創(chuàng)建的根IoC容器
獲取根IoC容器有兩種方法,還可通過key直接獲取
*/
WebApplicationContext rootContext =
WebApplicationContextUtils.getWebApplicationContext(getServletContext());
WebApplicationContext wac = null;
if (this.webApplicationContext != null) {
// A context instance was injected at construction time -> use it
wac = this.webApplicationContext;
if (wac instanceof ConfigurableWebApplicationContext) {
ConfigurableWebApplicationContext cwac = (ConfigurableWebApplicationContext) wac;
if (!cwac.isActive()) {
// The context has not yet been refreshed -> provide services such as
// setting the parent context, setting the application context id, etc
if (cwac.getParent() == null) {
// The context instance was injected without an explicit parent -> set
// the root application context (if any; may be null) as the parent
/*
如果當(dāng)前Servelt存在一個WebApplicationContext即子IoC容器
并且上文獲取的根IoC容器存在,則將根IoC容器作為子IoC容器的父容器
*/
cwac.setParent(rootContext);
}
//配置并刷新當(dāng)前的子IoC容器,功能與前文講解根IoC容器時的配置刷新一致,用于構(gòu)建相關(guān)Bean
configureAndRefreshWebApplicationContext(cwac);
}
}
}
if (wac == null) {
// No context instance was injected at construction time -> see if one
// has been registered in the servlet context. If one exists, it is assumed
// that the parent context (if any) has already been set and that the
// user has performed any initialization such as setting the context id
//如果當(dāng)前Servlet不存在一個子IoC容器則去查找一下
wac = findWebApplicationContext();
}
if (wac == null) {
// No context instance is defined for this servlet -> create a local one
//如果仍舊沒有查找到子IoC容器則創(chuàng)建一個子IoC容器
wac = createWebApplicationContext(rootContext);
}
if (!this.refreshEventReceived) {
// Either the context is not a ConfigurableApplicationContext with refresh
// support or the context injected at construction time had already been
// refreshed -> trigger initial onRefresh manually here.
//調(diào)用子類覆蓋的onRefresh方法完成“可變”的初始化過程
onRefresh(wac);
}
if (this.publishContext) {
// Publish the context as a servlet context attribute.
String attrName = getServletContextAttributeName();
getServletContext().setAttribute(attrName, wac);
if (this.logger.isDebugEnabled()) {
this.logger.debug("Published WebApplicationContext of servlet '" + getServletName() +
"' as ServletContext attribute with name [" + attrName + "]");
}
}
return wac;
}
通過函數(shù)名不難發(fā)現(xiàn),該方法的主要作用同樣是創(chuàng)建一個WebApplicationContext
對象,即Ioc容器
,不過前文講過每個Web應(yīng)用
最多只能存在一個根IoC容器
,這里創(chuàng)建的則是特定Servlet
擁有的子IoC容器
,可能有些讀者會有疑問,為什么需要多個Ioc容器
,首先介紹一個父子IoC容器
的訪問特性,有興趣的讀者可以自行實驗。
父子IoC容器的訪問特性
在學(xué)習(xí)Spring
時,我們都是從讀取xml配置文件
來構(gòu)造IoC容器
,常用的類有ClassPathXmlApplicationContext類
,該類存在一個初始化方法用于傳入xml文件
路徑以及一個父容器
,我們可以創(chuàng)建兩個不同的xml配置文件
并實現(xiàn)如下代碼:
//applicationContext1.xml文件中配置一個id為baseBean的Bean
ApplicationContext baseContext = new ClassPathXmlApplicationContext("applicationContext1.xml");
Object obj1 = baseContext.getBean("baseBean");
System.out.println("baseContext Get Bean " + obj1);
//applicationContext2.xml文件中配置一個id未subBean的Bean
ApplicationContext subContext = new ClassPathXmlApplicationContext(new String[]{"applicationContext2.xml"}, baseContext);
Object obj2 = subContext.getBean("baseBean");
System.out.println("subContext get baseContext Bean " + obj2);
Object obj3 = subContext.getBean("subBean");
System.out.println("subContext get subContext Bean " + obj3);
//拋出NoSuchBeanDefinitionException異常
Object obj4 = baseContext.getBean("subBean");
System.out.println("baseContext get subContext Bean " + obj4);
首先創(chuàng)建baseContext
沒有為其設(shè)置父容器
,接著可以成功獲取id
為baseBean
的Bean
,接著創(chuàng)建subContext
并將baseContext
設(shè)置為其父容器
,subContext
可以成功獲取baseBean
以及subBean
,最后試圖使用baseContext
去獲取subContext
中定義的subBean
,此時會拋出異常NoSuchBeanDefinitionException
,由此可見,父子容器
類似于類的繼承關(guān)系,子類可以訪問父類中的成員變量,而父類不可訪問子類的成員變量,同樣的,子容器
可以訪問父容器
中定義的Bean
,但父容器
無法訪問子容器
定義的Bean
。
通過上述實驗我們可以理解為何需要創(chuàng)建多個Ioc容器
,根IoC容器
做為全局共享的IoC容器
放入Web應(yīng)用
需要共享的Bean
,而子IoC容器
根據(jù)需求的不同,放入不同的Bean
,這樣能夠做到隔離,保證系統(tǒng)的安全性。
接下來繼續(xù)講解DispatcherServlet類
的子IoC容器
創(chuàng)建過程,如果當(dāng)前Servlet
存在一個IoC容器
則為其設(shè)置根IoC容器
作為其父類,并配置刷新該容器,用于構(gòu)造其定義的Bean
,這里的方法與前文講述的根IoC容器類似
,同樣會讀取用戶在web.xml
中配置的<servlet>
中的<init-param>
值,用于查找相關(guān)的xml配置文件
用于構(gòu)造定義的Bean
,這里不再贅述了。如果當(dāng)前Servlet
不存在一個子IoC容器
就去查找一個,如果仍然沒有查找到則調(diào)用
createWebApplicationContext()
方法去創(chuàng)建一個,查看該方法的源碼如下圖所示:
該方法用于創(chuàng)建一個子IoC容器
并將根IoC容器
做為其父容器,接著進(jìn)行配置和刷新操作用于構(gòu)造相關(guān)的Bean
。至此,根IoC容器
以及相關(guān)Servlet
的子IoC容器
已經(jīng)配置完成,子容器
中管理的Bean
一般只被該Servlet
使用,因此,其中管理的Bean
一般是“局部”的,如SpringMVC
中需要的各種重要組件,包括Controller
、Interceptor
、Converter
、ExceptionResolver
等。相關(guān)關(guān)系如下圖所示:
當(dāng)IoC子容器
構(gòu)造完成后調(diào)用了onRefresh()
方法,該方法的調(diào)用與initServletBean()
方法的調(diào)用相同,由父類調(diào)用但具體實現(xiàn)由子類覆蓋,調(diào)用onRefresh()
方法時將前文創(chuàng)建的IoC子容器
作為參數(shù)傳入,查看DispatcherServletBean類
的onRefresh()
方法源碼如下:
/**
* This implementation calls {@link #initStrategies}.
*/
//context為DispatcherServlet創(chuàng)建的一個IoC子容器
@Override
protected void onRefresh(ApplicationContext context) {
initStrategies(context);
}
/**
* Initialize the strategy objects that this servlet uses.
* <p>May be overridden in subclasses in order to initialize further strategy objects.
*/
protected void initStrategies(ApplicationContext context) {
initMultipartResolver(context);
initLocaleResolver(context);
initThemeResolver(context);
initHandlerMappings(context);
initHandlerAdapters(context);
initHandlerExceptionResolvers(context);
initRequestToViewNameTranslator(context);
initViewResolvers(context);
initFlashMapManager(context);
}
onRefresh()
方法直接調(diào)用了initStrategies()
方法,源碼如上,通過函數(shù)名可以判斷,該方法用于初始化創(chuàng)建multipartResovle
來支持圖片等文件的上傳、本地化解析器、主題解析器、HandlerMapping
處理器映射器、HandlerAdapter
處理器適配器、異常解析器、視圖解析器、flashMap管理器等,這些組件都是SpringMVC
開發(fā)中的重要組件,相關(guān)組件的初始化創(chuàng)建過程均在此完成。
由于篇幅問題本文不再進(jìn)行更深入的探討,有興趣的讀者可以閱讀本系列文章的其他博客內(nèi)容。
至此,DispatcherServlet類
的創(chuàng)建和初始化過程也就結(jié)束了,整個Web應(yīng)用
部署到容器后的初始化啟動過程的重要部分全部分析清楚了,通過前文的分析我們可以認(rèn)識到層次化設(shè)計的優(yōu)點,以及IoC容器
的繼承關(guān)系所表現(xiàn)的隔離性。分析源碼能讓我們更清楚的理解和認(rèn)識到相關(guān)初始化邏輯以及配置文件的配置原理。
總結(jié)
這里給出一個簡潔的文字描述版SpringMVC啟動過程
:
tomcat web容器啟動時會去讀取web.xml
這樣的部署描述文件
,相關(guān)組件啟動順序為: 解析<context-param>
=> 解析<listener>
=> 解析<filter>
=> 解析<servlet>
,具體初始化過程如下:
1、解析
<context-param>
里的鍵值對。2、創(chuàng)建一個
application
內(nèi)置對象即ServletContext
,servlet上下文,用于全局共享。3、將
<context-param>
的鍵值對放入ServletContext
即application
中,Web應(yīng)用
內(nèi)全局共享。-
4、讀取
<listener>
標(biāo)簽創(chuàng)建監(jiān)聽器,一般會使用ContextLoaderListener類
,如果使用了ContextLoaderListener類
,Spring
就會創(chuàng)建一個WebApplicationContext類
的對象,WebApplicationContext類
就是IoC容器
,ContextLoaderListener類
創(chuàng)建的IoC容器
是根IoC容器
為全局性的,并將其放置在appication
中,作為應(yīng)用內(nèi)全局共享,鍵名為WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE
,可以通過以下兩種方法獲取WebApplicationContext applicationContext = (WebApplicationContext) application.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE); WebApplicationContext applicationContext1 = WebApplicationContextUtils.getWebApplicationContext(application);
這個全局的根IoC容器
只能獲取到在該容器中創(chuàng)建的Bean
不能訪問到其他容器創(chuàng)建的Bean
,也就是讀取web.xml
配置的contextConfigLocation
參數(shù)的xml文件
來創(chuàng)建對應(yīng)的Bean
。
- 5、
listener
創(chuàng)建完成后如果有<filter>
則會去創(chuàng)建filter
。 - 6、初始化創(chuàng)建
<servlet>
,一般使用DispatchServlet類
。 - 7、
DispatchServlet
的父類FrameworkServlet
會重寫其父類的initServletBean
方法,并調(diào)用initWebApplicationContext()
以及onRefresh()
方法。 - 8、
initWebApplicationContext()
方法會創(chuàng)建一個當(dāng)前servlet
的一個IoC子容器
,如果存在上述的全局WebApplicationContext
則將其設(shè)置為父容器
,如果不存在上述全局的則父容器
為null。 - 9、讀取
<servlet>
標(biāo)簽的<init-param>
配置的xml文件
并加載相關(guān)Bean
。 - 10、
onRefresh()
方法創(chuàng)建Web應(yīng)用
相關(guān)組件。
備注
由于作者水平有限,難免出現(xiàn)紕漏,如有問題還請不吝賜教。