SpringBoot 項目 @EnableWebMvc 註解應用的總結

在spring-boot+spring mvc 的項目中,有我們需要自己配置一些項目的設置,就會涉及到三個類(@EnableWebMvc 、WebMvcConfigurationSupport和WebMvcConfigurationAdapter),那麼,他們之間有什麼關係呢? 
首先,@EnableWebMvc=WebMvcConfigurationSupport,使用了@EnableWebMvc註解等於擴展了WebMvcConfigurationSupport但是沒有重寫任何方法。
翻源代碼:

 @EnableWebMvc
 
 *  @see org.springframework.web.servlet.config.annotation.WebMvcConfigurer
 * @see org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport
 * @see org.springframework.web.servlet.config.annotation.DelegatingWebMvcConfiguration

有以下幾種使用方式:

@EnableWebMv + extends WebMvcConfigurationAdapter,在擴展的類中重寫父類的方法即可(友情提示,最新版spring boot 因爲jdk已經支持接口默認方法實現,所以WebMvcConfigurationAdapter已經過時),這種方式會屏蔽springboot的@EnableAutoConfiguration中的設置

extends WebMvcConfigurationSupport,在擴展的類中重寫父類的方法即可,這種方式會屏蔽springboot的@EnableAutoConfiguration中的設置

extends WebMvcConfigurationAdapter,在擴展的類中重寫父類的方法即可,這種方式依舊使用springboot的@EnableAutoConfiguration中的設置
 

有時候我們我們需要自定義一些配置

比如:Spring Boot 定製HTTP消息轉換器

 

總結

使用 @EnableWebMvc 註解會屏蔽springboot的@EnableAutoConfiguration,需要自己設置MessageConverter;

默認使用 @EnableAutoConfiguration 註解,讀取 application.properties 或 application.yml 文件中的配置。

 

參考

https://blog.csdn.net/testcs_dn/article/details/80249894

https://blog.csdn.net/pomer_huang/article/details/77170673

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章