SpringMVC源码学习笔记之DispatcherServlet

一、什么是DispatcherServlet

在整个SpringMVC框架中,DispatcherServlet处于核心位置,它负责协调和组织不同组件完成请求处理并返回响应工作。DispatcherServlet是SpringMVC统一的入口,所有的请求都通过它。

我们先看下DispatcherServlet的类图

可以看到DispatcherServlet本质上是一个Servlet,而我们知道Servlet的生命周期是init -> service -> destroy,下面我们看看DispatcherServlet的初始化过程,也就是init方法

二、DispatcherServlet的初始化过程

DispatcherServlet的init方法在其父类HttpServletBean里

//HttpServletBean
@Override
public final void init() throws ServletException {

    // 这里是读取xml配置,不重要
    PropertyValues pvs = new ServletConfigPropertyValues(getServletConfig(), this.requiredProperties);
    if (!pvs.isEmpty()) {
        try {
            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();
}

跟着23行initServletBean进去,来到子类FrameworkServlet中

//FrameworkServlet
@Override
protected final void initServletBean() throws ServletException {
    //打印一些日志
    getServletContext().log("Initializing Spring " + getClass().getSimpleName() + " '" + getServletName() + "'");
    if (logger.isInfoEnabled()) {
        logger.info("Initializing Servlet '" + getServletName() + "'");
    }
    long startTime = System.currentTimeMillis();

    try {
        //重点是这个,初始化WebApplicationContext
        //WebApplicationContext是SpringMVC的IOC容器
        this.webApplicationContext = initWebApplicationContext();
        initFrameworkServlet();
    }
    catch (ServletException | RuntimeException ex) {
        logger.error("Context initialization failed", ex);
        throw ex;
    }

    if (logger.isDebugEnabled()) {
        String value = this.enableLoggingRequestDetails ?
                "shown which may lead to unsafe logging of potentially sensitive data" :
                "masked to prevent unsafe logging of potentially sensitive data";
        logger.debug("enableLoggingRequestDetails='" + this.enableLoggingRequestDetails +
                "': request parameters and headers will be " + value);
    }

    if (logger.isInfoEnabled()) {
        logger.info("Completed initialization in " + (System.currentTimeMillis() - startTime) + " ms");
    }
}

点击13行initWebApplicationContext进去

//FrameworkServlet
protected WebApplicationContext initWebApplicationContext() {
    //获取WebApplicationContext,Spring容器
    WebApplicationContext rootContext =
            WebApplicationContextUtils.getWebApplicationContext(getServletContext());
    WebApplicationContext wac = null;

    if (this.webApplicationContext != null) {
        // 如果WebApplicationContext不为空,说明该类在构造时已经将其注入
        wac = this.webApplicationContext;
        if (wac instanceof ConfigurableWebApplicationContext) {
            ConfigurableWebApplicationContext cwac = (ConfigurableWebApplicationContext) wac;
            if (!cwac.isActive()) {
                if (cwac.getParent() == null) {
                    //将Spring的容器设为SpringMVC容器的父容器
                    cwac.setParent(rootContext);
                }
                configureAndRefreshWebApplicationContext(cwac);
            }
        }
    }
    if (wac == null) {
        //如果WebApplicationContext为空,则进行查找,能找到说明上下文已经在别处初始化
        wac = findWebApplicationContext();
    }
    if (wac == null) {
        //如果WebApplicationContext还是空,就以Spring的容器为父容器建一个新的
        wac = createWebApplicationContext(rootContext);
    }

    if (!this.refreshEventReceived) {
        synchronized (this.onRefreshMonitor) {
            //模版方法,由子类DispatcherServlet实现
            onRefresh(wac);
        }
    }

    if (this.publishContext) {
        //发布这个WebApplicationContext容器到ServletContext中.
        String attrName = getServletContextAttributeName();
        getServletContext().setAttribute(attrName, wac);
    }

    return wac;
}

点击34行onRefresh来到子类DispatcherServlet里

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

//初始化SpringMVC的九大组件
protected void initStrategies(ApplicationContext context) {
    //多文件上传组件
    initMultipartResolver(context);
    //多语言支持组件
    initLocaleResolver(context);
    //主题模板处理组件
    initThemeResolver(context);
    //URL映射组件
    initHandlerMappings(context);
    //业务逻辑适配组件
    initHandlerAdapters(context);
    //异常处理组件
    initHandlerExceptionResolvers(context);
    //视图名称提取组件
    initRequestToViewNameTranslator(context);
    //视图渲染组件
    initViewResolvers(context);
    //闪存管理组件
    initFlashMapManager(context);
}

总结:

GenericServlet接收上下文对象,HttpServletBean给属性赋值,FrameworkServlet负责创建并初始化WebApplicationContext容器,最后DispatcherServlet初始化九大组件

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

每天进步亿点点的小码农

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值