WebMvcConfigurationSupport和WebMvcConfigurer
SpringBoot幫我們做了很多的事情,但是有的時候會有自定義的Handler,Interceptor,ViewResolver,MessageConverter等,該怎麼配置呢?為什麼繼承了WebMvcConfigurationSupport後有些配置會不生效呢?WebMvcConfigurer又是什麼呢?
WebMvcConfigurationSupport
我們繼承WebMvcConfigurationSupport可以自定義SpringMvc的配置。
跟蹤發現DelegatingWebMvcConfiguration類是WebMvcConfigurationSupport的一個實現類,DelegatingWebMvcConfiguration類的setConfigurers方法可以收集所有的WebMvcConfigurer實現類中的配置組合起來,組成一個超級配置(這些配置會覆蓋掉預設的配置)。而@EnableWebMvc又引入了DelegatingWebMvcConfiguration。
所以,我們繼承了WebMvcConfigurationSupport,而後使用@EnableWebMvc會覆蓋掉原來的配置。
WebMvcConfigurer
WebMvcConfigurer配置類其實是Spring內部的一種配置方式,採用JavaBean的形式來代替傳統的xml配置檔案形式進行鍼對框架個性化定製。
在官方文件中有這麼一段話:
>
If you want to keep Spring Boot MVC features and you want to add additional MVC configuration (interceptors, formatters, view controllers, and other features), you can add your own @Configuration class of type WebMvcConfigurer but without @EnableWebMvc.
所以,如果我們想要在Auto-configuration的基礎上配置自定義的interceptors, formatters, view controllers等功能話,我們可以實現WebMvcConfigurer,並用@Configuration註釋。
WebMvcConfigurer的主要方法有:
- configurePathMatch:配置路由請求規則
- configureContentNegotiation:內容協商配置
- configureAsyncSupport
- configureDefaultServletHandling:預設靜態資源處理器
- addFormatters:註冊自定義轉化器
- addInterceptors:攔截器配置
- addResourceHandlers:資源處理
- addCorsMappings:CORS配置
- addViewControllers:檢視跳轉控制器
- configureViewResolvers:配置檢視解析
- addArgumentResolvers:新增自定義方法引數處理器
- addReturnValueHandlers:新增自定義返回結果處理器
- configureMessageConverters:配置訊息轉換器。過載會覆蓋預設註冊的HttpMessageConverter
- extendMessageConverters:配置訊息轉換器。僅新增一個自定義的HttpMessageConverter.
- configureHandlerExceptionResolvers:配置異常轉換器
- extendHandlerExceptionResolvers:新增異常轉化器
- getValidator
- getMessageCodesResolver
使用方式
- 使用@EnableWebMvc註解 等於 擴充套件了WebMvcConfigurationSupport,但是沒有重寫任何方法
- 使用“extends WebMvcConfigurationSupport”方式(需要新增@EnableWebMvc),會遮蔽掉springBoot的@EnableAutoConfiguration中的設定
- 使用“implement WebMvcConfigurer”可以配置自定義的配置,同時也使用了@EnableAutoConfiguration中的設定
- 使用“implement WebMvcConfigurer + @EnableWebMvc”,會遮蔽掉springBoot的@EnableAutoConfiguration中的設定
這裡的“@EnableAutoConfiguration中的設定”是指,讀取 application.properties 或 application.yml 檔案中的配置。
所以,如果需要使用springBoot的@EnableAutoConfiguration中的設定,那麼就只需要“implement WebMvcConfigurer”即可。如果,需要自己擴充套件同時不使用@EnableAutoConfiguration中的設定,可以選擇另外的方式。