SpringMVC源码解析-0xml配置原理

image.png

前言

看一段官网原话:

Spring MVC, as many other web frameworks, is designed around the front controller pattern where a central Servlet, the DispatcherServlet, provides a shared algorithm for request processing, while actual work is performed by configurable delegate components. This model is flexible and supports diverse workflows.
翻译:Spring MVC 与许多其他 Web 框架一样,围绕前端控制器模式设计,其中中央 Servlet DispatcherServlet 为请求处理提供共享算法,而实际工作由可配置的委托组件执行。 该模型非常灵活,支持多种工作流程。

The DispatcherServlet, as any Servlet, needs to be declared and mapped according to the Servlet specification by using Java configuration or in web.xml. In turn, the DispatcherServlet uses Spring configuration to discover the delegate components it needs for request mapping, view resolution, exception handling, and more.
翻译:DispatcherServlet 与任何 Servlet 一样,需要根据 Servlet 规范通过使用 Java 配置或在 web.xml 中进行声明和映射。 反过来,DispatcherServlet 使用 Spring 配置来发现请求映射、视图解析、异常处理等所需的委托组件。

官网提供了两种方式配置示例注册并初始化 DispatcherServlet的demo:

  1. JavaConfig方式
public class MyWebApplicationInitializer implements WebApplicationInitializer {

    @Override
    public void onStartup(ServletContext servletContext) {

        // Load Spring web application configuration
        AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
        context.register(AppConfig.class);

        // Create and register the DispatcherServlet
        DispatcherServlet servlet = new DispatcherServlet(context);
        ServletRegistration.Dynamic registration = servletContext.addServlet("app", servlet);
        registration.setLoadOnStartup(1);
        registration.addMapping("/app/*");
    }
}

  1. web.xml方式
<web-app>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/app-context.xml</param-value>
    </context-param>

    <servlet>
        <servlet-name>app</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value></param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>app</servlet-name>
        <url-pattern>/app/*</url-pattern>
    </servlet-mapping>

</web-app>

推荐使用JavaConfig方式配置,无需xml文件,维护方便。

0 xml配置原理

从前面JavaConfig方式的demo中可以看出想要注册并初始化 DispatcherServlet,需要实现WebApplicationInitializer接口并重写onStartup(ServletContext context)方法。

WEB容器会在启动的时候去调onStartup方法。

这里说的WEB容器其实是一个Application Server,或者更准确的来说,是一个支持运行Servlet/JSP应用程序的容器。
比如:Tomcat 、JBoss、Jetty等。

通过传参ServletContext 用来注册web组件:

image.png

那么onStart方法是如何生效的呢?是谁调用的?

我们实现的WebApplicationInitializer接口是springframework给提供的接口,那他是如何被web容器给调用的呢?

package org.springframework.web;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;

public interface WebApplicationInitializer {
    void onStartup(ServletContext servletContext) throws ServletException;
}

前面官方文档中提到DispatcherServlet 与任何 Servlet 一样,需要根据 Servlet 规范通过使用 Java 配置或在 web.xml 中进行声明和映射。什么是 Servlet 规范?

servlet规范是WEB框架在Servlet容器中运行时需要遵循的一种标准。
如果WEB框架想要在符合Servlet规范的容器中运行,那么它需要符合Servlet规范。
Servlet是Java对于Web开发而产生的一项技术,可以说Servlet技术是Java专有的。
学习链接: Java™ Servlet 规范,针对版本是 3.1。本文档描述了 Java Servlet API 的标准。

servlet 3.0版本以后提出的一个新规范SPI:
你的项目里面如果有某些类或者某些方法需要在启动的时候被Tomcat(Web容器)调用的话,首先你在你的项目的根目录的 META-INF/services/ javax.servlet.ServletContainerInitializer目录下指定一个文件。

image.png

可以看出spring在遵从servlet规范的javax.servlet.ServletContainerInitializer中的指定了一个spring自己的类:org.springframework.web.SpringServletContainerInitializer。

@HandlesTypes({WebApplicationInitializer.class})
public class SpringServletContainerInitializer implements ServletContainerInitializer {
    public SpringServletContainerInitializer() {
    }

    public void onStartup(@Nullable Set<Class<?>> webAppInitializerClasses, ServletContext servletContext) throws ServletException {
        //省略部分代码-----------
        while(var4.hasNext()) {
                WebApplicationInitializer initializer = (WebApplicationInitializer)var4.next();
                //关键代码
                initializer.onStartup(servletContext);
       }
    }
}

而SpringServletContainerInitializer类实现了ServletContainerInitializer接口,ServletContainerInitializer接口是javax.servlet包中提供的接口(即是servlet规范开发提供的接口),它也有一个onStartup方法,该方法会在容器启动的时候被调用。

public interface ServletContainerInitializer {
    void onStartup(Set<Class<?>> var1, ServletContext var2) throws ServletException;
}

那这个Servlet提供的ServletContainerInitializer接口的onStartup方法是怎么和Spring框架提供的WebApplicationInitializer接口的onStartup方法联系起来的呢?

刚才我们说的SpringServletContainerInitializer类实现了ServletContainerInitializer接口,该类上使用了注解@HandlesTypes({WebApplicationInitializer.class}),并重写了onStartup方法,该方法第一个参数是Set<Class<?>>;

@HandlesTypes注解由Servlet容器提供支持(实现),参数中指定的所有实现类,利用字节码扫描框架(例如ASM、BCEL)从classpath中扫描出来,放入集合,传给回调方法onStartup的第一个参数,然后执行其实现类的onStartup(servletContext)。

经此就显而易见了,我们的WebApplicationInitializer接口实现类就是在SpringServletContainerInitializer类中被循环调用的,在web容器启动后会调用ServletContainerInitializer实现类的onStartup方法,而该onStartup方法又会去调用我们的WebApplicationInitializer接口实现类中的onStartup方法,从而注册并初始化 DispatcherServlet以及其他web组件。

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,242评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,769评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,484评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,133评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,007评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,080评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,496评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,190评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,464评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,549评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,330评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,205评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,567评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,889评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,160评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,475评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,650评论 2 335

推荐阅读更多精彩内容