springboot自动装配了WebMvc,通过WebMvcAutoConfiguration.class源码可以查看自动装配类中默认的WebMvc配置
如果想要扩展WebMvc,只需要创建一个配置类实现WebMvcConfigurer接口即可
@Configuration
public class MyMVCConfig implements WebMvcConfigurer {
}
这个配置类上不建议使用@EnableWebMvc注解,因为@EnableWebMvc注解会全面接管WebMvc,而springboot自动装配的WebMvc配置则全部失效。
那么为什么@EnableWebMvc注解能够全面接管springboot的Mvc配置呢?
1.查看自动配置类WebMvcAutoConfiguration.class源码
可以看到标红注解,这个注解表示如果WebMvcConfigurationSupport.class类不存在,自动配置类WebMvcAutoConfiguration.class才会生效
2.查看@EnableWebMvc源码
可以看到导入了一个DelegatingWebMvcConfiguration.class,点进该类进行查看
发现该类继承了WebMvcConfigurationSupport类
而WebMvcAutoConfiguration.class中明确声明了@ConditionalOnMissingBean(WebMvcConfigurationSupport.class)
因此WebMvcAutoConfiguration便失效了