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是哪里来的?如下图,当然是从容器中拿的啦:

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

  • 相关阅读:
    设计模式的六大原则 ---- 理论知识
    动手编写TCP服务器系列之一:日志文件
    Shell语言系列之一:文件处理
    给Amazon ec2 增加卷(Volume)并挂载到系统
    Java打包问题之一:打包出现java.io.IOException: invalid header field
    struct中长度为0的数组用途与原理
    child和childNodes的区别
    学习es6 setter/getter研究
    tabIndex-bootstrap中Get到的
    tml兼容性
  • 原文地址:https://www.cnblogs.com/restart30/p/10813066.html
Copyright © 2011-2022 走看看