首先,確認你是對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是哪裏來的?以下圖,固然是從容器中拿的啦:
至此,相關代碼都串起來嘍。