Spring MVC之组件初始化

1.Spring MVC整体结构介绍

Spring MVC主要类结构图

Spring MVC之组件初始化_第1张图片
image

从上图中可以看到在Servlet的继承结构中一共有5个类,分别是Java提供的两个类GenericServlet,HttpServlet和Spring MVC提供的三个类HttpServletBean、FrameworkServlet和Dispat
cherServlet

Spring MVC请求流程图


Spring MVC之组件初始化_第2张图片
image

从上图可以看出DispatcherServlet是Spring MVC框架的核心,通过DispatcherServlet获取处理请求的Handler
Adapter(处理请求的具体Controller),然后将返回的结果交给ViewResolver(处理视图的类),然后渲染出视图返回给客户端

2.HttpServletBean

通过前面的文章,我们知道搭建SpringMVC框架的时候在web.xml文件中配置了DispatcherServlet,它是Spring MVC控制器的核心,当系统开始运行时,DispatcherServlet就开始初始化(1),由于DispatcherServlet类本身没有init初始化方法,它的父类中只有HttpServletBean中有inti初始化方法,HttpServletBean的初始化方法如下:

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

        try {
            //将Servlet中配置的参数封装到ex变量中,requiredProperties为必须参数,如果没有配置则报异常
            HttpServletBean.ServletConfigPropertyValues ex = new HttpServletBean.ServletConfigPropertyValues(this.getServletConfig(), this.requiredProperties);
            BeanWrapper bw =PropertyAccessorFactory.forBeanPropertyAccess(this);
            ServletContextResourceLoader resourceLoader = new ServletContextResourceLoader(this.getServletContext());
            bw.registerCustomEditor(Resource.class, new ResourceEditor(resourceLoader, this.getEnvironment()));
            //模板方法,调用的是FrameworkServlet中的初始化方法,做一些初始化工作。bw代表DispatcherServlet
            this.initBeanWrapper(bw);
            //将配置的初始化值(如ContextConfigLocation)设置到DispatcherServlet中
            bw.setPropertyValues(ex, true);
        } catch (BeansException var4) {
            this.logger.error("Failed to set bean properties on servlet \'" + this.getServletName() + "\'", var4);
            throw var4;
        }
        //模板方法,FrameworkServlet初始化的入口方法
        this.initServletBean();
        if(this.logger.isDebugEnabled()) {
            this.logger.debug("Servlet \'" + this.getServletName() + "\' configured successfully");
        }

    }
HttpServletBean.ServletConfigPropertyValues ex = new HttpServletBean.ServletConfigPropertyValues(this.getServletConfig(), this.requiredProperties);
//getServletConfig()方法是Servlet接口提供的方法用于获取ServletConfig,当Servlet的init方法被调用时,会接受到一个ServletConfig类型的参数,指的是Servlet的配置,在web.xml中定义Servlet时通过init-param标签配置的参数就是通过ServletConfig保存的。

BeanWrapper 是Spring提供的一个用来操作JavaBean属性的工具,使用它可以直接修改一个对象的属性

BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(this);  
//通过PropertyAccessorFactory对象的forBeanPropertyAccess方法将DispatcherServlet封装成BeanWrapper对象,这样通过bw变量就可以对DispatcherServlet的属性进行操作
3.FrameworkServlet

从上面HttpServletBean中的初始化代码得知,FrameworkServlet的初始化入口方法是initServletBean

    protected final void initServletBean() throws ServletException {
        this.getServletContext().log("Initializing Spring FrameworkServlet \'" + this.getServletName() + "\'");
        if(this.logger.isInfoEnabled()) {
            this.logger.info("FrameworkServlet \'" + this.getServletName() + "\': initialization started");
        }

        long startTime = System.currentTimeMillis();

        try {
            //初始化WebApplicationContext
            this.webApplicationContext = this.initWebApplicationContext();
            //初始化FrameworkServlet
            this.initFrameworkServlet();
        } catch (ServletException var5) {
            this.logger.error("Context initialization failed", var5);
            throw var5;
        } catch (RuntimeException var6) {
            this.logger.error("Context initialization failed", var6);
            throw var6;
        }

        if(this.logger.isInfoEnabled()) {
            long elapsedTime = System.currentTimeMillis() - startTime;
            this.logger.info("FrameworkServlet \'" + this.getServletName() + "\': initialization completed in " + elapsedTime + " ms");
        }

    }

首先查看WebApplicationContext初始化代码;WebApplicationContext是web应用的上下文环境

  protected WebApplicationContext initWebApplicationContext() {
        //通过getServletContext获取的ServletContext来获取根上下文
        WebApplicationContext rootContext = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
        WebApplicationContext wac = null;
        //如果已经通过构造方法设置了webApplicationContext
        if(this.webApplicationContext != null) {
            wac = this.webApplicationContext;
            if(wac instanceof ConfigurableWebApplicationContext) {
                ConfigurableWebApplicationContext attrName = (ConfigurableWebApplicationContext)wac;
                if(!attrName.isActive()) {
                    if(attrName.getParent() == null) {
                        attrName.setParent(rootContext);
                    }

                    this.configureAndRefreshWebApplicationContext(attrName);
                }
            }
        }

        if(wac == null) {
            //如果webApplicationContext已经存在ServletContext中时,通过配置在Servlet中的参数获取
            wac = this.findWebApplicationContext();
        }

        if(wac == null) {
            //创建一个新的webApplicationContext
            wac = this.createWebApplicationContext(rootContext);
        }

        if(!this.refreshEventReceived) {
            //模板方法,HttpServletBean中用来初始化Spring MVC的九大组件
            this.onRefresh(wac);
        }

        if(this.publishContext) {
            //将ApplicationContext保存到ServletContext中
            String attrName1 = this.getServletContextAttributeName();
            this.getServletContext().setAttribute(attrName1, wac);
            if(this.logger.isDebugEnabled()) {
                this.logger.debug("Published WebApplicationContext of servlet \'" + this.getServletName() + "\' as ServletContext attribute with name [" + attrName1 + "]");
            }
        }

        return wac;
    }
    

获取spinrg的根容器rootContext
WebApplicationContext rootContext=WebApplicationContextUtils.getWebApplicationContext(this.getServl
etContext());

设置webApplicationContext并根据情况调用onRefresh方法

设置webApplicationContext的三种方法

  • 在构造方法中已经传递了webApplicationContext参数,这时只需要对其进行一些设置即可
  • webApplicationContext已经在ServletContext中了,这时只需要在配置Servlet的时候将ServletContext中的webApplicationContext的name配置到contextAttribute属性就可以了
  • 前面两种方式都无效的情况下,通过createWebApplicationContext来创建一个

创建webApplicationContext的方法

protected WebApplicationContext createWebApplicationContext(
ApplicationContext parent) {
        //通过getContextClass获取要创建的类型
        Class contextClass = this.getContextClass();
        if(this.logger.isDebugEnabled()) {
            this.logger.debug("Servlet with name \'" + this.getServletName() + "\' will try to create custom WebApplicationContext context of class \'" + contextClass.getName() + "\'" + ", using parent context [" + parent + "]");
        }

        if(!ConfigurableWebApplicationContext.class.isAssignableFrom(contextClass)) {
            throw new ApplicationContextException("Fatal initialization error in servlet with name \'" + this.getServletName() + "\': custom WebApplicationContext class [" + contextClass.getName() + "] is not of type ConfigurableWebApplicationContext");
        } else {
            //具体创建
            ConfigurableWebApplicationContext wac = (ConfigurableWebApplicationContext)BeanUtils.instantiateClass(contextClass);
            wac.setEnvironment(this.getEnvironment());
            wac.setParent(parent);
            //将设置的contextConfigLocation参数传给wac,默认传入WEB-INF/[ServletName]-servlet.xml
            wac.setConfigLocation(this.getContextConfigLocation());
            this.configureAndRefreshWebApplicationContext(wac);
            return wac;
        }
    }

将webApplicationContext设置到ServletContext中

    if(this.publishContext) {
        //将ApplicationContext保存到ServletContext中
        String attrName1 = this.getServletContextAttributeName();
        this.getServletContext().setAttribute(attrName1, wac);
        if(this.logger.isDebugEnabled()) {
            this.logger.debug("Published WebApplicationContext of servlet \'" + this.getServletName() + "\' as ServletContext attribute with name [" + attrName1 + "]");
        }
    }

根据publishContext标志判断是否将webApplicationContext设置到ServletContext的属性中,publishContext标志可以在配置Servlet时通过init-param参数进行设置,HttpServletBean初始化时会将其设置到publishContext参数

3.DispatcherServlet

onRefresh方法是DispatcherServlet的入口方法

    protected void onRefresh(ApplicationContext context) {
        this.initStrategies(context);
    }

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

onRefresh方法调用了initStrategies方法,initStrategies方法中初始化了Spring MVC九大组件

4.小结

上面主要分析了Spring MVC自身的创建过程,Spring MVC中的Servlet一共分为三个层
次,分别是HttpServletBean、FrameworkServlet和DispatcherServlet。

  • HttpServletBean继承自Java的HttpServlet,其作用是将Servlet中配置的参数设置到相应的属性
  • FrameworkServlet初始化了WebApplicationContext
  • DispatcherServlet初始化了自身的9大组件

你可能感兴趣的:(Spring MVC之组件初始化)