springmvc中Dispatchservlet继承体系详解

一、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的工作流程

———————————原创文章,转载请说明—————————————————

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值