springmvc中Dispatchservlet繼承體系詳解

Nevermoretoo發表於2018-11-12

一、Dispatchservlet繼承體系

springmvc繼承體系

在這一篇文章中,我主要說一下HttpServletBean、FrameworkServlet、DispatcherServlet的建立過程

首先,我們看到這三個類直接實現了3個介面:EnvironmentCapable、EnvironmentAware、ApplicationContextAware。我們先來看下這3個介面都能幹什麼

  1. ApplicationContextAware:類似如XXXAware型的介面,表示對XXX可以進行感知,通俗解釋就是:如果在某個類中想要使用spring的一些東西,就可以通過實現XXXAware介面來告訴spring,spring看到後就能給你傳送過來,而接收的方式就是通過實現該介面的唯一方法setXXX()。
public interface ApplicationContextAware extends Aware {

	/**
	 * Set the ApplicationContext that this object runs in.
	 * Normally this call will be used to initialize the object.
	 * <p>Invoked after population of normal bean properties but before an init callback such
	 * as {@link org.springframework.beans.factory.InitializingBean#afterPropertiesSet()}
	 * or a custom init-method. Invoked after {@link ResourceLoaderAware#setResourceLoader},
	 * {@link ApplicationEventPublisherAware#setApplicationEventPublisher} and
	 * {@link MessageSourceAware}, if applicable.
	 * @param applicationContext the ApplicationContext object to be used by this object
	 * @throws ApplicationContextException in case of context initialization errors
	 * @throws BeansException if thrown by application context methods
	 * @see org.springframework.beans.factory.BeanInitializationException
	 */
	void setApplicationContext(ApplicationContext applicationContext) throws BeansException;

}
  1. EnvironmentAware同上
  2. EnvironmentCapable:顧名思義,該介面表示具有Environment的能力,也就是可以提供Environment,該介面唯一的方法就是getEnvironment(),它將返回一個Environment物件。
public interface EnvironmentCapable {

	/**
	 * Return the {@link Environment} associated with this component.
	 */
	Environment getEnvironment();

}

在HttpServletBean中的Environment裡面封裝了ServletContext、ServletConfig、JndiProperty、系統環境變數和系統屬性,這裡都封裝到了其propertySources屬性下。在實際開發中,當web容器初始化後,在web.xml中對DispatcherServlet設定的init-param就會封裝到Environment裡面:

<init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath*:/spring/spring-mvc*.xml</param-value>
</init-param>

看完整體結構,接下來分別看一下spring中三個類的具體建立過程。

二、HttpServletBean

我們知道,在servlet建立過程中可以直接呼叫無參的Init方法,HttpServletBean的init方法如下:

@Override
	public final void init() throws ServletException {
		if (logger.isDebugEnabled()) {
			logger.debug("Initializing servlet '" + getServletName() + "'");
		}

		// 將servlet中配置的引數封裝到pvs變數中,requiredProperties為必需引數
		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()));
			//模板方法,可以在子類呼叫,做初始化工作,bw代表dispatchServlet物件
			initBeanWrapper(bw);
			//將配置好的初始化值(如contextConfigLocation)設定到dispatchServlet中
			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");
		}
	}

在這段程式碼中,首先將servlet中配置的引數使用BeanWrapper設定到DispatchServlet的相關屬性,然後呼叫模板方法initServletBean(),子類就通過該方法初始化。其中BeanWrapper是spring提供的一個用來操作JavaBean屬性的工具,使用它可以直接修改一個物件的屬性。

三、FrameworkServlet

由上面對HttpServletBean的分析可知,FrameworkServlet的初始化入口方法應該是initServletBean,其程式碼如下:

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

這裡的核心程式碼只有2句,一句用於初始化WebApplicationContext,另一句用於初始化FrameworkServlet,而且initFrameworkServlet()方法為模板方法,子類可以覆蓋然後在裡面做一下初始化的工作,但它的子類如DispatchServlet並沒有使用它。可見,FrameworkServlet在構建的過程中主要的作用就是為了初始化WebApplicationContext,下面,我們來看一下initWebApplicationContext方法:

/**
	 * 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() {
		//獲取rootContext
		WebApplicationContext rootContext =
				WebApplicationContextUtils.getWebApplicationContext(getServletContext());
		WebApplicationContext wac = null;

		//如果已經通過構造方法設定了WebApplicationContext
		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) {
			//當WebApplicationContext已經存在於servletContext中時,通過配置在servlet中的contextAttribute引數獲取
			wac = findWebApplicationContext();
		}
		if (wac == null) {
			//如果WebApplicationContext還沒有建立,那麼就建立一個
			wac = createWebApplicationContext(rootContext);
		}

		//只有當webApplicationcontext是通過第二種方法設定的時候才會走這一段程式碼
		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) {
			// 將ApplicationContext儲存到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;
	}

initWebApplicationContext共做了三件事:

  1. 獲取spring的根容器rootContext
  2. 設定WebApplicationContext並根據情況呼叫onRefresh方法
  3. 將WebApplicationContext設定到ServletContext中

1.獲取spring的根容器rootContext:
預設情況下,spring會將自己的容器設定成servletContext的屬性,所以獲取根容器只需要呼叫servletContext的getAttribute就可以了。

2.設定WebApplicationContext並根據情況呼叫onRefresh方法:

設定WebApplicationContext一共有3種方法:
① 在構造方法中已經傳遞了WebApplicationContext引數,這時只需再對其進行設定即可。這種方法主要用於servlet3.0之後的環境,可以在程式中使用servletContext.addServlet方法註冊servlet。這時就可以在新建FrameworkServlet和其子類的時候就通過構造方法傳遞已經準備好的WebApplicationContext。
② WebApplicationContext已經存在於servletContext中了,這時只需要在配置servlet的時候將servletContext中的WebApplicationContext配置到contextAttribute屬性就可以了
③ 在前面2種方法都無效的情況下使用,通常都是使用這種方法。

注意:第三種方法的內部方法中,已經refresh()了,不需用在通過initWebApplicationContext()中的onRefresh()方法來refresh了。同樣的,在第一種設定WebApplicationContext的方法中,也同樣refresh過,所以只有在第二種方法的情況下,才會呼叫initWebApplicationContext()中的onRefresh()方法。不過不管通過哪種方式呼叫,onRefresh()方法肯定且只會呼叫一次,而且dispatchServlet正是通過重寫這個模板方法來實現初始化的

3.將WebApplicationContext設定到ServletContext中
最後,會根據publishContext標誌來判斷是否將建立出來的WebApplicationContext設定到servletContext中,publishContext可以在配置servlet時通過init-param引數設定,HttpServletBean初始化時會將其設定到publishContext引數,之所以將WebApplicationContext設定到servletContext中,是為了方便獲取。
此外,我介紹一下配置servlet時可以設定的初始化引數:

  1. contextAttribute:在servletContext的屬性中,用作與webApplicationContext的屬性名
  2. contextClass:建立webApplicationContext的型別
  3. contextConfigLocation:springmvc配置檔案的位置
  4. publishContext:是否將webApplicationContext設定到servletContext的屬性。

四、DispatcherServlet

onRefresh方法是DispatcherServlet的入口方法。onRefresh方法簡單的呼叫了initStrategis()。在裡面呼叫了9個初始化方法:

	/**
	 * This implementation calls {@link #initStrategies}.
	 */
	@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);
	}

initStrategies方法非常簡單,目的就是初始化springmvc的9大元件,下面以LocaleResolver為例:

/**
	 * Initialize the LocaleResolver used by this class.
	 * <p>If no bean is defined with the given name in the BeanFactory for this namespace,
	 * we default to AcceptHeaderLocaleResolver.
	 */
	private void initLocaleResolver(ApplicationContext context) {
		try {
			this.localeResolver = context.getBean(LOCALE_RESOLVER_BEAN_NAME, LocaleResolver.class);
			if (logger.isDebugEnabled()) {
				logger.debug("Using LocaleResolver [" + this.localeResolver + "]");
			}
		}
		catch (NoSuchBeanDefinitionException ex) {
			// We need to use the default.
			this.localeResolver = getDefaultStrategy(context, LocaleResolver.class);
			if (logger.isDebugEnabled()) {
				logger.debug("Unable to locate LocaleResolver with name '" + LOCALE_RESOLVER_BEAN_NAME +
						"': using default [" + this.localeResolver + "]");
			}
		}
	}

初始化方式分2步:首先通過context.getBean()在容器中按註冊時的名稱或型別來進行查詢,所以在springmvc的配置檔案中,只需要配置相應型別的元件時就能查詢到,沒找到也會有一個預設值,預設值通過getDefaultStrategy()方法來獲取。

相對來說。DispatcherServlet的建立還是相對簡單一些,複雜的工作父類已經代替它完成了,它主要的工作就是註冊配置檔案中配置的9大元件,關於9大元件,我之後的文章將會做介紹,下一篇打算寫一下DispatcherServlet的工作流程

———————————原創文章,轉載請說明—————————————————

相關文章