SpringMVC DispatcherServlet原始碼解析

z1340954953發表於2018-07-19

DispatcherServlet繼承關係

 初始化過程分析

* 呼叫HttpServletBean的init方法(內部的initServletBean方法是空方法,交由FrameworkServlet實現)

DispatcherServlet中沒有定義init方法,是從httpservlet中繼承過來的,在HttpServletBean中重寫

HttpServletBean中init方法

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

1. 先看下第一行程式碼,建立一個PropertyValues

將servletconfig獲取到的servlet的初始化引數和值,建立propertyvalue物件,新增到propertyValueList中

public ServletConfigPropertyValues(ServletConfig config, Set<String> requiredProperties)
			throws ServletException {

			Set<String> missingProps = (requiredProperties != null && !requiredProperties.isEmpty()) ?
					new HashSet<String>(requiredProperties) : null;

			Enumeration<String> en = config.getInitParameterNames();
			while (en.hasMoreElements()) {
				String property = en.nextElement();
				Object value = config.getInitParameter(property);
				addPropertyValue(new PropertyValue(property, value));
				if (missingProps != null) {
					missingProps.remove(property);
				}
			}

			// Fail if we are still missing properties.
			if (missingProps != null && missingProps.size() > 0) {
				throw new ServletException(
					"Initialization from ServletConfig for servlet '" + config.getServletName() +
					"' failed; the following required properties were missing: " +
					StringUtils.collectionToDelimitedString(missingProps, ", "));
			}
		}
	}

2. 給當前的物件生成BeanWrapper物件(這個BeanWrapper類是一個不通過建立物件,通過建立PropertyValue設定物件的屬性值) ,關於BeanWrapper的介紹

3. 呼叫BeanWrapper物件的setPropertyValues,設定DispatcherServlet的初始化引數。

4. 呼叫initServletBean方法,在HTTPServletBean中是空方法,由DispatcherServlet的上一級父類FrameworkServlet實現

protected void initServletBean() throws ServletException {
	}

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

 建立webApplicationContext(這個介面繼承自ApplicationContext)並設定到ServletContext中,這樣將web容器和Spring上下文關聯起來了。

具體細節

protected WebApplicationContext initWebApplicationContext() {
		//獲取根上下文
		WebApplicationContext rootContext =
				WebApplicationContextUtils.getWebApplicationContext(getServletContext());
		WebApplicationContext wac = null;
		//DispatcherServlet的構造器中如果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);
					}
					//設定webApplicationContext
					configureAndRefreshWebApplicationContext(cwac);
				}
			}
		}
		if (wac == null) {
			//根據contextAttribute屬性來獲取webapplicationContext,一般設定DispatcherServlet的屬性時候不設定,這裡就不執行
			wac = findWebApplicationContext();
		}
		if (wac == null) {
			//DispatcherServlet初始化最終呼叫的方法,建立上下文,並配置上下文的父上下文
			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);//將建立的容器上下文設定到ServletContext中
			if (this.logger.isDebugEnabled()) {
				this.logger.debug("Published WebApplicationContext of servlet '" + getServletName() +
						"' as ServletContext attribute with name [" + attrName + "]");
			}
		}

		return wac;
	}

這裡的根上下文是web.xml中配置的ContextLoaderListener監聽器中根據contextConfigLocation路徑生成的上下文。

<context-param>
  <param-name>contextConfigLocation</param-name>  
  <param-value>classpath:springConfig/applicationContext.xml</param-value>  
</context-param>
<listener>
  <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>  
</listener>

onRefresh方法會在DispatcherServlet中重寫,用於初始化springMVC的元件

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

總結

1. HttpServletBean 

將web.xml中配置的servlet引數設定到DispatcherServlet的屬性上

2. FrameworkServlet

建立WebApplicationContext並設定到ServletContext上,將SpringMVC的上下文和servlet容器關聯,

WebApplicationContext有個父類的上下文,既web.xml中配置的ContextLoaderListener監聽器初始化的容器上下文。

3.DispatcherServlet 

初始化springMVC依賴的各個元件

參考: http://www.cnblogs.com/fangjian0423/p/springMVC-dispatcherServlet.html

相關文章