Spring MVC啟動流程分析


本文是Spring MVC系列博客的第一篇,后續會匯總成貼子。


Spring MVC是Spring系列框架中使用頻率最高的部分。不管是Spring Boot還是傳統的Spring項目,只要是Web項目都會使用到Spring MVC部分。因此程序員一定要熟練掌握MVC部分。本篇博客就簡要分析下Spring MVC的啟動流程,幫助我們更好的理解這個框架。


為什么要寫這篇博客

Spring的MVC框架已經出來很久了,網上介紹這部分的博客有很多很多,而且很多肯定比我自己寫的好,那我還為什么要寫這篇博客呢。一方面我覺得博客是對自己學習過程的一個記錄,另一方面寫博客的過程能加深自己對相關技術的理解,也方便以后自己回顧總結。

Spring MVC簡介

什么是Spring MVC

要回答這個問題,我們先要說說MVC。MVC是一種設計模式,這種設計模式建議將一個請求由M(Module)、V(View)、C(controller)三個部分進行處理。請求先經過controller,controller調用其他服務層得到Module,最后將Module數據渲染成試圖(View)返回客戶端。Spring MVC是Spring生態圈的一個組件,一個遵守MVC設計模式的WEB MVC框架。這個框架可以和Spring無縫整合,上手簡單,易於擴展。

解決什么問題

通常我們將一個J2EE項目項目分為WEB層、業務邏輯層和DAO層。Spring MVC解決的是WEB層的編碼問題。Spring MVC作為一個框架,抽象了很多通用代碼,簡化了WEB層的編碼,並且支持多種模板技術。我們不需要像以前那樣:每個controller都對應編寫一個Servlet,請求JSP頁面返回給前台。

優缺點

用的比較多的MVC框架有Struts2和Spring MVC。兩者之間的對比

  • 最大的一個區別就是Struts2完全脫離了Servlet容器,而SpringMVC是基於Servlet容器的;
  • Spring MVC的核心控制器是Servlet,而Struts2是Filter;
  • Spring MVC默認每個Controller是單列,而Struts2每次請求都會初始化一個Action;
  • Spring MVC配置較簡單,而Struts2的配置更多還是基於XML的配置。

總的來說,Spring MVC比較簡單,學習成本低,和Spring能無縫集成。在企業中也得到越來越多的應用。所以個人比較建議在項目中使用Spring MVC。

啟動流程分析

PS:本文的分析還是基於傳統的Tomcat項目分析,因為這個是基礎。現在非常流行的Spring Boot項目中的啟動流程后續也會寫文章分析。其實原理差不多...

要分析Spring MVC的啟動過程,要從它的啟動配置說起。一般會在Tomcat的 Web.xml中配置了一個ContextLoaderListener和一個DispatcherServlet。其實ContextLoaderListener是可以不配,這樣的話Spring會將所有的bean放入DispatcherServlet初始化的上下文容器中管理。這邊我們就拿常規的配置方式說明Spring MVC的啟動過程。(PS:Spring Boot啟動過程已經不使用Web.xml)

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >


<!--一個web應用對應一個ServletContext實例,這個實例是應用部署啟動后,servlet容器為應用創建的。
    ServletContext實例包含了所有servlet共享的資源信息。通過提供一組方法給servlet使用,用來
    和servlet容器通訊,比如獲取文件的MIME類型、分發請求、記錄日志等。
    http://www.cnblogs.com/nantang/p/5919323.html -->
<web-app>
	<display-name>Archetype Created Web Application</display-name>

	<context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:beans.spring.xml</param-value>
    </context-param>
	<context-param>
		<param-name>webAppRootKey</param-name>
		<param-value>project.root.path</param-value>
	</context-param>

	<!-- 將項目的絕對路徑放到系統變量中 -->
	<listener>
		<listener-class>org.springframework.web.util.WebAppRootListener</listener-class>
	</listener>
	<!--初始化Spring IOC容器,並將其放到servletContext的屬性當中-->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener> 
     
	<!-- 配置SPRINGMVC-->
	<servlet>
		<servlet-name>springmvc</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>classpath:springmvc.spring.xml</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>
	<servlet-mapping>
		<servlet-name>springmvc</servlet-name>
		<!-- 這邊不建議寫成/* -->
		<url-pattern>/</url-pattern>
	</servlet-mapping>

</web-app>

Tomcat啟動的時候會依次加載web.xml中配置的Listener、Filter和Servlet。所以根據上面的配置,會首先加載ContextLoaderListener,這個類繼承了ContextLoader,用來初始化Spring根上下文,並將其放入ServletContext中。下面就以這個為入口分析下代碼。

Tomcat容器首先會調用調用ContextLoadListener的contextInitialized()方法,這個方法又調用了父類ContextLoader的initWebApplicationContext()方法。下面是這個方法的源代碼。

public WebApplicationContext initWebApplicationContext(ServletContext servletContext) {
//如果ServletContext中已經存在Spring容器則報錯
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.
		if (this.context == null) {
            //這里創建了webApplicationContext,默認創建的是XmlWebApplicationContext
            //如果想要自定義實現類,可以在web.xml的<context-param>中配置contextClass這個參數
            //此時的Context還沒進行配置,相當於只是個"空殼"
			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.
					ApplicationContext parent = loadParentContext(servletContext);
					cwac.setParent(parent);
				}
                //讀取Spring的配置文件,初始化父上下文環境
				configureAndRefreshWebApplicationContext(cwac, servletContext);
			}
		}
        //將根上下文存入ServletContext中。
    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;
	}
}

至此,Spring的父(根)上下文已經初始化完畢,並且已經存在ServletContext中。

下面開始分析子上下文的初始化過程。這個過程通過Spring MVC的核心Servlet完成,所以我們也有必要講下Servlet的生命周期。請求過來,判斷Servlet有沒創建,沒有實例化並調用init方法,后面再調用service方法。我們在配置DispatcherServlet的時候,將其設置為啟動時創建實例,所以Tomcat在啟動的時候就會創建Spring的子上下文。

下面是DispatcherServlet的繼承結構。

GenericServlet (javax.servlet)
    HttpServlet (javax.servlet.http)
        HttpServletBean (org.springframework.web.servlet)
            FrameworkServlet (org.springframework.web.servlet)
                DispatcherServlet (org.springframework.web.servlet)

DispatcherServlet繼承了FrameworkServlet,FrameworkServlet又繼承了HttpServletBean,HttpServletBean又繼承HttpServlet並且重寫了init方法,所以創建子上下文時的入口就在這個init方法。

//HttpServletBean的init是入口方法
@Override
public final void init() throws ServletException {
	if (logger.isDebugEnabled()) {
		logger.debug("Initializing servlet '" + getServletName() + "'");
	}
	// Set bean properties from init parameters.
	try {
        //讀取Servlet配置的init-param,創建DispatcherServlet實例
		PropertyValues pvs = new ServletConfigPropertyValues(getServletConfig(), this.requiredProperties);
		BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(this);
		ResourceLoader resourceLoader = new ServletContextResourceLoader(getServletContext());
		bw.registerCustomEditor(Resource.class, new ResourceEditor(resourceLoader, getEnvironment()));
		initBeanWrapper(bw);
		bw.setPropertyValues(pvs, true);
	}
	catch (BeansException ex) {
		if (logger.isErrorEnabled()) {
			logger.error("Failed to set bean properties on servlet '" + getServletName() + "'", ex);
		}
		throw ex;
	}
	// HttpServletBean的這個方法中沒有做任何事情,子類FrameWorkServlet這個類的initServletBean()方法重寫了
    // 這個類,所以后續工作會在這個方法中執行。
	initServletBean();
	if (logger.isDebugEnabled()) {
		logger.debug("Servlet '" + getServletName() + "' configured successfully");
	}
}

下面是FrameWorkServlet這個類的initServletBean()方法

//FrameWorkServlet.initServletBean()
protected final void initServletBean() throws ServletException {
	getServletContext().log("Initializing Spring FrameworkServlet '" + getServletName() + "'");
	if (this.logger.isInfoEnabled()) {
		this.logger.info("FrameworkServlet '" + getServletName() + "': initialization started");
	}
	long startTime = System.currentTimeMillis();

	try {
        //這里是重點,初始化子Spring上下文
		this.webApplicationContext = initWebApplicationContext();
		initFrameworkServlet();
	}
	catch (ServletException ex) {
		this.logger.error("Context initialization failed", ex);
		throw ex;
	}
	catch (RuntimeException ex) {
		this.logger.error("Context initialization failed", ex);
		throw ex;
	}

	if (this.logger.isInfoEnabled()) {
		long elapsedTime = System.currentTimeMillis() - startTime;
		this.logger.info("FrameworkServlet '" + getServletName() + "': initialization completed in " +
				elapsedTime + " ms");
	}
}

下面是initWebApplicationContext()方法的具體代碼

protected WebApplicationContext initWebApplicationContext() {
	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
					cwac.setParent(rootContext);
				}
				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
		wac = findWebApplicationContext();
	}
	if (wac == null) {
		// No context instance is defined for this servlet -> create a local one
        // 這邊是重點,創建Spring子上下文,並將設置其父類上下文
		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.
		onRefresh(wac);
	}

	if (this.publishContext) {
		// 將Spring子上下文存入ServletContext
		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;
}

最后看下DispatcherServlet中的onRefresh()方法,這個方法初始化了很多策略:

protected void initStrategies(ApplicationContext context) {
	initMultipartResolver(context);
	initLocaleResolver(context);
	initThemeResolver(context);
	initHandlerMappings(context);
	initHandlerAdapters(context);
	initHandlerExceptionResolvers(context);
	initRequestToViewNameTranslator(context);
	initViewResolvers(context);
	initFlashMapManager(context);
}

到此為止,SpringMVC的啟動過程結束了。這邊做下SpringMVC初始化總結(不是很詳細)

  • HttpServletBean的主要做一些初始化工作,將我們在web.xml中配置的參數書設置到Servlet中;
  • FrameworkServlet主要作用是初始化Spring子上下文,設置其父上下文,並將其和ServletContext關聯;
  • DispatcherServlet:初始化各個功能的實現類。比如異常處理、視圖處理、請求映射處理等。

簡單總結

傳統的Spring MVC項目啟動流程如下:

  • 如果在web.xml中配置了org.springframework.web.context.ContextLoaderListener,那么Tomcat在啟動的時候會先加載父容器,並將其放到ServletContext中;
  • 然后會加載DispatcherServlet(這塊流程建議從init方法一步步往下看,流程還是很清晰的),因為DispatcherServlet實質是一個Servlet,所以會先執行它的init方法。這個init方法在HttpServletBean這個類中實現,其主要工作是做一些初始化工作,將我們在web.xml中配置的參數書設置到Servlet中,然后再觸發FrameworkServlet的initServletBean()方法;
  • FrameworkServlet主要作用是初始化Spring子上下文,設置其父上下文,並將其放入ServletContext中;
  • FrameworkServlet在調用initServletBean()的過程中同時會觸發DispatcherServlet的onRefresh()方法,這個方法會初始化Spring MVC的各個功能組件。比如異常處理器、視圖處理器、請求映射處理等。(注意這個onRefresh方法,這個方法做了很多事情,建議仔細看下)

博客參考


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM