Springmvc入门(十)DispatcherServlet初始化源码分析

DispatchServlet作为springmvc核心类,以下是它的结构图

Aware接口,比如实现了ApplicationContextAware接口的类,能够获取到ApplicationContext。

DispatcherServer的构造器

先初始化父类的,然后设置一个父类属性的值,将http请求直接发送到doService方法

        public DispatcherServlet() {
		super();
        //设置属性,是否将http请求发送到doService方法
		setDispatchOptionsRequest(true);
	}


	public DispatcherServlet(WebApplicationContext webApplicationContext) {
		super(webApplicationContext);
		setDispatchOptionsRequest(true);
	}

FrameworkServlet的构造器,继续对父类的HttpServletBean类进行构建

        public FrameworkServlet() {
	}

	public FrameworkServlet(WebApplicationContext webApplicationContext) {
		this.webApplicationContext = webApplicationContext;
	}

HttpServletBean中的init初始化方法

init中调用了两个模板方法,可以由子类去实现

initServletBean就是子类FrameworkServlet的入口方法

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

		//将servlet的参数封装到pvs中,requiredProperties是必须参数
		PropertyValues pvs = new ServletConfigPropertyValues(getServletConfig(), this.requiredProperties);
		if (!pvs.isEmpty()) {
			try {
				//创建并给DispatchServlet赋值
				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;
			}
		}

		//调用子类方法
		initServletBean();

		if (logger.isDebugEnabled()) {
			logger.debug("Servlet '" + getServletName() + "' configured successfully");
		}
	}
	
	protected void initBeanWrapper(BeanWrapper bw) throws BeansException {
	}

	
	protected void initServletBean() throws ServletException {
	}

FrameworkServlet的initServletBean的方法

initFrameworkServlet也是一个模板方法,由子类提供实现,不过子类没实现

onRefresh模板方法,子类提供

        @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 {
			//初始化WebApplicationContext
			this.webApplicationContext = initWebApplicationContext();
			//子类可覆盖此方法,做一些初始化工作,不过子类没实现
			initFrameworkServlet();
		}
		catch (ServletException | 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");
		}
	}
	
	protected WebApplicationContext initWebApplicationContext() {
		//获取rootContext
		WebApplicationContext rootContext =
				WebApplicationContextUtils.getWebApplicationContext(getServletContext());
		WebApplicationContext wac = null;
		//如果已经通过构造方法构造了webApplicationContext
		if (this.webApplicationContext != null) {
			wac = this.webApplicationContext;
			if (wac instanceof ConfigurableWebApplicationContext) {
				ConfigurableWebApplicationContext cwac = (ConfigurableWebApplicationContext) wac;
				if (!cwac.isActive()) {			
					if (cwac.getParent() == null) {	
						cwac.setParent(rootContext);
					}
					configureAndRefreshWebApplicationContext(cwac);
				}
			}
		}
		if (wac == null) {
			//当webApplicationContext已经存在servletContext,通过servlet配置的参数进行获取
			wac = findWebApplicationContext();
		}
		if (wac == null) {
			//不存在,则创一个webApplicationContext
			wac = createWebApplicationContext(rootContext);
		}
		if (!this.refreshEventReceived) {
		//当ContextRefreshedEvent没有触发时调用此方法
		//子类DispatchServlet类方法的入口
			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;
	}
	
	protected void initFrameworkServlet() throws ServletException {
	}

DispatcherServlet的onRefresh方法对自己的九大组件进行初始化

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

	
	protected void initStrategies(ApplicationContext context) {
	//初始化DispatchServlet的九大组件
		initMultipartResolver(context);
		initLocaleResolver(context);
		initThemeResolver(context);
		initHandlerMappings(context);
		initHandlerAdapters(context);
		initHandlerExceptionResolvers(context);
		initRequestToViewNameTranslator(context);
		initViewResolvers(context);
		initFlashMapManager(context);
	}

	
	private void initMultipartResolver(ApplicationContext context) {
		//假设有配置多部分文件传输
		try {
			this.multipartResolver = context.getBean(MULTIPART_RESOLVER_BEAN_NAME, MultipartResolver.class);
			if (logger.isDebugEnabled()) {
				logger.debug("Using MultipartResolver [" + this.multipartResolver + "]");
			}
		}
		catch (NoSuchBeanDefinitionException ex) {
			// 默认是没有
			this.multipartResolver = null;
			if (logger.isDebugEnabled()) {
				logger.debug("Unable to locate MultipartResolver with name '" + MULTIPART_RESOLVER_BEAN_NAME +
						"': no multipart request handling provided");
			}
		}
	}

	
	private void initThemeResolver(ApplicationContext context) {
		try {
			//再context中获取,只要在配置文件中配置了bean,就能找到
			this.themeResolver = context.getBean(THEME_RESOLVER_BEAN_NAME, ThemeResolver.class);
			if (logger.isDebugEnabled()) {
				logger.debug("Using ThemeResolver [" + this.themeResolver + "]");
			}
		}
		catch (NoSuchBeanDefinitionException ex) {
			// 假设没有,则使用默认是主题解析类
			//再dispatch.properties可知,默认的主题解析类org.springframework.web.servlet.theme.FixedThemeResolver
			this.themeResolver = getDefaultStrategy(context, ThemeResolver.class);
			if (logger.isDebugEnabled()) {
				logger.debug("Unable to locate ThemeResolver with name '" + THEME_RESOLVER_BEAN_NAME +
						"': using default [" + this.themeResolver + "]");
			}
		}
	}

小结:

HttpServletBean继承HttpServlet,是将servlet中的配置的参数映射到相对应的属性上,FrameworkServlet主要是创建并初始化WebApplicationContext,DispatcherServlet初始化了自身的九大组件,采用了大量的模板方法,由父类去调用子类的方法。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值