zoukankan      html  css  js  c++  java
  • spring boot中扩展spring mvc 源码分析

    首先,确认你是对spring boot的自动配置相关机制是有了解的,如果不了解请看我spring boot相关的源码分析。

    通常的使用方法是继承自org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration.WebMvcAutoConfigurationAdapter,然后重写

    org.springframework.web.servlet.config.annotation.WebMvcConfigurer.addInterceptors(InterceptorRegistry)等方法。

    spring mvc的自动配置类是org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration

    里面有内部类org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration.WebMvcAutoConfigurationAdapter供扩展继承。

    以及org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration.EnableWebMvcConfiguration对应的启用webMvc,同@EnableWebMvc注解功能相同。

    父类org.springframework.web.servlet.config.annotation.DelegatingWebMvcConfiguration的setConfigurers方法加了@Autowired注解,会自动将容器中实现了org.springframework.web.servlet.config.annotation.WebMvcConfigurer接口的bean注入进来。上面的WebMvcAutoConfigurationAdapter就是实现了WebMvcConfigurer这个接口,

    所以我们扩展时的子类都会被注册进DelegatingWebMvcConfiguration。这个里面的addInterceptors代理了刚刚所有注册进来的WebMvcAutoConfigurationAdapter子类。

    那么,什么时候调用addInterceptors呢?答案就是DelegatingWebMvcConfiguration的父类WebMvcConfigurationSupport的getInterceptors中调用了addInterceptors,如下图所示:

    那么又是哪里需要获取这些拦截器呢?如下图所示,在WebMvcConfigurationSupport中定义了很多HandlerMapping的实现bean,熟悉spring mvc的人应该很清楚,一个请求上来经过spirng mvc的时候,正是这些HandlerMapping处理的前端请求。

    spring mvc的入口在org.springframework.web.servlet.DispatcherServlet.doService(HttpServletRequest, HttpServletResponse),里面调用doDispatch做分发处理,方法如下,其中的getHandler就是根据HttpServletRequest获取对应的执行类:

     getHandler中的this.handlerMappings是哪里来的?如下图,当然是从容器中拿的啦:

    至此,相关代码都串起来喽。

  • 相关阅读:
    Spring Boot 内嵌Tomcat的端口号的修改
    仅显示INPUT下边框
    2015面试记三
    2015面试记二
    2015面试记一
    最近工作学习心得体会
    Tomcat批处理文件小结
    启动Tomcat一闪而过——分析及解决过程
    WIN7安装及配置JDK
    Firefox下载文件时中文名乱码问题
  • 原文地址:https://www.cnblogs.com/restart30/p/10813066.html
Copyright © 2011-2022 走看看