一、概述
? ? ? ? 作為Spring家族的明星產品,SpringBoot極大地簡化了程序員的日常開發,提高了開發效率。我們很容易得借助于SpringBoot就可以快速開發業務代碼。一般情況下,公司的日常開發都是基于web服務的,我們在使用idea等工具初始化一個springboot項目時,一般都會在pom.xml中加入 spring-boot-starter-web 依賴,引入了這個依賴后,springmvc相關的依賴就都引入進來并通過springboot的自動化配置給我們配置好了,如下:
? ? ? ? 但是,真實的項目環境下,系統自帶的配置不一定能滿足我們的實際需求,這就需要我們結合實際業務進行自定義配置了。
二、SpringMVC配置相關的類
????????WebMvcConfigurer(Interface)、WebMvcConfigurerAdapter(Class,新版本已廢棄)、WebMvcConfigurationSupport(Class)、@EnableWebMvc(注解)
2.1、WebMvcConfigurerAdapter
????????WebMvcConfigurerAdapter是springboot 1.x中定義的一個類,在1.x版本中,自定義springmvc的配置就可以通過繼承WebMvcConfigurerAdapter實現的,這個抽象類本身實現了WebMvcConfigurer接口,2.x及以上版本已廢棄,源碼如下:
/*** An implementation of {@link WebMvcConfigurer} with empty methods allowing* subclasses to override only the methods they're interested in.** @author Rossen Stoyanchev* @since 3.1*/
public abstract class WebMvcConfigurerAdapter implements WebMvcConfigurer {//...}
2.2、WebMvcConfigurer
????????WebMvcConfigurer是一個接口,接口中的方法和 WebMvcConfigurerAdapter 中定義的空方法其實一樣,所以用法上來說,基本上沒有差別,從 Spring Boot 1.x 切換到 Spring Boot 2.x ,只需要把繼承類改成實現即可,在springboot2.x及以上版本,如果我們有自定義SpringMVC的需求,可以通過實現 WebMvcConfigurer 接口來配置,源碼如下:
/*** Defines callback methods to customize the Java-based configuration for* Spring MVC enabled via {@code @EnableWebMvc}.** <p>{@code @EnableWebMvc}-annotated configuration classes may implement* this interface to be called back and given a chance to customize the* default configuration.** @author Rossen Stoyanchev* @author Keith Donald* @author David Syer* @since 3.1*/
public interface WebMvcConfigurer {// ...}
?2.3、WebMvcConfigurationSupport
????????WebMvcConfigurationSupport是一個類,一般用于ssm(spring+springmvc+mybatis)的項目中,自定義類通過繼承WebMvcConfigurationSupport,可以在不寫springmvc.xml配置的情況下,實現對mvc的配置,例如:
注意事項:
????????WebMvcConfigurationSupport禁止在springboot中使用!因為在springboot中如果使用了WebMvcConfigurationSupport,將會導致SpringBoot中的MVC自動配置失效,SpringBoot中的mvc的自動化配置類是WebMvcAutoConfiguration,其源碼如下:
? ? ? ? 很明顯的可以看到SpringBoot中WebMvcAutoConfiguration生效的前提是當前資源目錄下無WebMvcConfigurationSupport,所以在在springboot中禁止使用WebMvcConfigurationSupport!!!
2.4、@EnableWebMvc
????????@EnableWebMvc是一個注解,?它的作用是啟用WebMvcConfigurationSupport,通過2.3的源碼分析,所以在springboot中也不建議使用,因為它也會導致SpringBoot的WebMvcAutoConfiguration失效,源碼如下: