首先,确认你是对spring boot的自动配置相关机制是有了解的,若是不了解请看我spring boot相关的源码分析。前端
一般的使用方法是继承自org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration.WebMvcAutoConfigurationAdapter,而后重写web
org.springframework.web.servlet.config.annotation.WebMvcConfigurer.addInterceptors(InterceptorRegistry)等方法。spring
spring mvc的自动配置类是org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfigurationmvc
里面有内部类org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration.WebMvcAutoConfigurationAdapter供扩展继承。app
以及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这个接口,this
因此咱们扩展时的子类都会被注册进DelegatingWebMvcConfiguration。这个里面的addInterceptors代理了刚刚全部注册进来的WebMvcAutoConfigurationAdapter子类。spa
那么,何时调用addInterceptors呢?答案就是DelegatingWebMvcConfiguration的父类WebMvcConfigurationSupport的getInterceptors中调用了addInterceptors,以下图所示:代理
那么又是哪里须要获取这些拦截器呢?以下图所示,在WebMvcConfigurationSupport中定义了不少HandlerMapping的实现bean,熟悉spring mvc的人应该很清楚,一个请求上来通过spirng mvc的时候,正是这些HandlerMapping处理的前端请求。blog
spring mvc的入口在org.springframework.web.servlet.DispatcherServlet.doService(HttpServletRequest, HttpServletResponse),里面调用doDispatch作分发处理,方法以下,其中的getHandler就是根据HttpServletRequest获取对应的执行类:
getHandler中的this.handlerMappings是哪里来的?以下图,固然是从容器中拿的啦:
至此,相关代码都串起来喽。