1. 程式人生 > >【Spring MVC】DispatcherServlet詳解(容器初始化超詳細過程原始碼分析)

【Spring MVC】DispatcherServlet詳解(容器初始化超詳細過程原始碼分析)

DispatcherServlet類相關的結構圖

DispatcherServlet的初始化程式

DispatcherServlet初始化了什麼,可以在其initStrategies()方法中知曉,這個方法如下:

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

需要做的八件事情如下所述:

  • initMultipartResolver:初始化MultipartResolver,用於處理檔案上傳服務,如果有檔案上傳,那麼就會將當前的HttpServletRequest包裝成DefaultMultipartHttpServletRequest,並且將每個上傳的內容封裝成CommonsMultipartFile物件。需要在dispatcherServlet-servlet.xml中配置檔案上傳解析器。
  • initLocaleResolver:用於處理應用的國際化問題,本地化解析策略。
  • initThemeResolver:用於定義一個主題。
  • initHandlerMapping:用於定義請求對映關係。
  • initHandlerAdapters:用於根據Handler的型別定義不同的處理規則。
  • initHandlerExceptionResolvers:當Handler處理出錯後,會通過此將錯誤日誌記錄在log檔案中,預設實現類是SimpleMappingExceptionResolver。
  • initRequestToViewNameTranslators:將指定的ViewName按照定義的RequestToViewNameTranslators替換成想要的格式。
  • initViewResolvers:用於將View解析成頁面。
  • initFlashMapManager:用於生成FlashMap管理器。

Spring MVC容器的初始化過程

首先,我們從web.xml中開始,在web.xml中我們首先配置的是contextLoaderListener,它的作用就是啟動web容器時,自動裝配ApplicationContext的配置資訊。因為它實現了ServletContextListener這個介面,在web.xml配置這個監聽器,啟動容器時,就會自動執行它實現的contextInitialized()方法。這樣就能夠在客戶端請求之前向ServletContext中新增任意的物件。

在ServletContextListener中的核心邏輯便是初始化WebApplicationContext例項並存放至ServletContext中

public void contextInitialized(ServletContextEvent event) {
		this.contextLoader = createContextLoader();
		if (this.contextLoader == null) {
			this.contextLoader = this;
		}
		this.contextLoader.initWebApplicationContext(event.getServletContext());
	}

這是ContextLoaderListener中的contextInitialized()方法,這裡主要是用initWebApplicationContext()方法來初始化WebApplicationContext。這裡涉及到一個常用類WebApplicationContext:它繼承自ApplicationContext,在ApplicationContext的基礎上又追加了一些特定於Web的操作及屬性。

這邊的操作就非常類似通過程式設計的方式使用Spring時使用ClassPathXmlApplicationContext類提供的功能。

public WebApplicationContext initWebApplicationContext(ServletContext servletContext) {
		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) {
				this.context = createWebApplicationContext(servletContext);
			}
			if (this.context instanceof ConfigurableWebApplicationContext) {
				configureAndRefreshWebApplicationContext((ConfigurableWebApplicationContext)this.context, 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;
		}
	}

在initWebApplicationContext()方法中主要體現了WebApplicationContext例項的建立過程。首先,驗證WebApplicationContext的存在性,通過檢視ServletContext例項中是否有對應key的屬性驗證WebApplicationContext是否已經建立過例項。如果沒有通過createWebApplicationContext()方法來建立例項,並存放至ServletContext中。

	protected WebApplicationContext createWebApplicationContext(ServletContext sc) {
		Class<?> contextClass = determineContextClass(sc);
		if (!ConfigurableWebApplicationContext.class.isAssignableFrom(contextClass)) {
			throw new ApplicationContextException("Custom context class [" + contextClass.getName() +
					"] is not of type [" + ConfigurableWebApplicationContext.class.getName() + "]");
		}
		ConfigurableWebApplicationContext wac =
				(ConfigurableWebApplicationContext) BeanUtils.instantiateClass(contextClass);
		return wac;
	}
在createWebApplicationContext()方法中,通過BeanUtils.instanceClass()方法建立例項,而WebApplicationContext的實現類名稱則通過determineContextClass()方法獲得。
	protected Class<?> determineContextClass(ServletContext servletContext) {
		String contextClassName = servletContext.getInitParameter(CONTEXT_CLASS_PARAM);
		if (contextClassName != null) {
			try {
				return ClassUtils.forName(contextClassName, ClassUtils.getDefaultClassLoader());
			}
			catch (ClassNotFoundException ex) {
				throw new ApplicationContextException(
						"Failed to load custom context class [" + contextClassName + "]", ex);
			}
		}
		else {
			contextClassName = defaultStrategies.getProperty(WebApplicationContext.class.getName());
			try {
				return ClassUtils.forName(contextClassName, ContextLoader.class.getClassLoader());
			}
			catch (ClassNotFoundException ex) {
				throw new ApplicationContextException(
						"Failed to load default context class [" + contextClassName + "]", ex);
			}
		}
	}

determineContextClass()方法,通過defaultStrategies.getProperty()方法獲得實現類的名稱,而defaultStrategies是在ContextLoader類的靜態程式碼塊中賦值的。具體的途徑,則是讀取ContextLoader類的同目錄下的ContextLoader.properties屬性檔案來確定的。

也就是說,在初始化的過程中,程式會首先讀取ContextLoader類的同目錄下的屬性檔案ContextLoader.properties,並根據其中的配置提取將要實現WebApplicationContext介面的實現類,並根據這個類通過反射進行例項的建立。

綜合以上的程式碼,ContextLoaderListener監聽器的作用就是啟動Web容器時,自動裝配ApplicationContext的配置資訊。因為它實現了ServletContextListener這個介面,在web.xml配置了這個監聽器,啟動容器時,就會預設執行它實現的contextInitialized()方法初始化WebApplicationContext例項,並放入到ServletContext中。由於在ContextLoaderListener中關聯了ContextLoader這個類,所以整個載入配置過程由ContextLoader來完成。

diapatcherServlet的初始化過程

DispatcherServlet實現了Servlet介面的實現類。Servlet的生命週期分為3個階段:初始化、執行和銷燬。而其初始化階段可分為:

  • Servlet容器載入Servlet類,把類的.class檔案中的資料讀到記憶體中;
  • Servlet容器中建立一個ServletConfig物件。該物件中包含了Servlet的初始化配置資訊;
  • Servlet容器建立一個Servlet物件;
  • Servlet容器呼叫Servlet物件的init()方法進行初始化。
Servlet的初始化階段會呼叫它的init()方法,DispatcherServlet也不例外,在它的父類HttpServletBean中找到了該方法
public final void init() throws ServletException {
		if (logger.isDebugEnabled()) {
			logger.debug("Initializing servlet '" + getServletName() + "'");
		}

		// Set bean properties from init parameters.
		try {
			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) {
			logger.error("Failed to set bean properties on servlet '" + getServletName() + "'", ex);
			throw ex;
		}

		// Let subclasses do whatever initialization they like.
		initServletBean();

		if (logger.isDebugEnabled()) {
			logger.debug("Servlet '" + getServletName() + "' configured successfully");
		}
	}

init()方法中先通過ServletConfigPropertiesValues()方法對Servlet初始化引數進行封裝,然後再將這個Servlet轉換成一個BeanWrapper物件,從而能夠以spring的方式來對初始化引數的值進行注入。這些屬性如contextConfigLocation、namespace等等。同時註冊一個屬性編輯器,一旦在屬性注入的時候遇到Resource型別的屬性就會使用ResourceEditor去解析。再留一個initBeanWrapper(bw)方法給子類覆蓋,讓子類處真正執行BeanWrapper的屬性注入工作。但是HttpServletBean的子類FrameworkServlet和DispatcherServlet都沒有覆蓋其initBeanWrapper(bw)方法,所以建立的BeanWrapper物件沒有任何作用。

程式接著往下走,執行到了initServletBean()方法。在之前,ContextLoaderListener載入的時候已經建立了WebApplicationContext例項,而在這裡是對這個例項的進一步補充初始化。這個方法在HttpServletBean的子類FrameworkServlet中得到了重寫。

注:ContextLoaderListener載入的是除DispatcherServlet之外的其他的上下文配置檔案,而Spring MVC的配置檔案是在DispatcherServlet中設定的。

	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 {
			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");
		}
	}

在initServletBean()方法中,設計了一個計時器來統計初始化的執行時間,還提供了一個initFrameworkServlet()用於子類的覆蓋操作,而作為關鍵的初始化邏輯給了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
			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) {
			// 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;
	}

initWebApplicationContext()方法主要用於建立或重新整理WebApplicationContext例項,並對Servlet功能所使用的變數進行初始化。它獲得ContextLoaderListener中初始化的rootContext。再通過建構函式和Servlet的contextAttribute屬性查詢ServletContext來進行webApplicationContext例項的初始化,如果都不行,只能重新建立一個新的例項。最終都要執行configureAndRefreshWebApplicationContext()方法中的refresh()方法完成servlet中配置檔案的載入和與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);
		}

onRefresh(wac)方法是FrameworkServlet提供的模板方法,在其子類DispatcherServlet的onRefresh()方法中進行了重寫。而在onRefresh()方法中呼叫了initStrategies()方法來完成初始化工作,初始化Spring MVC的9個元件。

@Override
protected void onRefresh(ApplicationContext context) {
	initStrategies(context);
}

具體的時序圖