SpringBoot [WebMvcConfigurationSupport/WebMvcConfigurer]等相关类区别

关于SpringMVC 的配置相关类:

    1. @EnableWebMvc
    1. @EnableAutoConfiguration
    1. WebMvcConfigurationSupport
    1. DelegatingWebMvcConfiguration
    1. WebMvcConfigurer
    1. WebMvcConfigurationAdapter(springboot2.0已废弃)

@EnableWebMvc 是什么

直接看源码,@EnableWebMvc实际上引入一个DelegatingWebMvcConfiguration类。


SpringBoot [WebMvcConfigurationSupport/WebMvcConfigurer]等相关类区别_第1张图片
图1:@EnableWebMvc 代码

DelegatingWebMvcConfiguration 继承了WebMvcConfigurationSupport


SpringBoot [WebMvcConfigurationSupport/WebMvcConfigurer]等相关类区别_第2张图片
图2:DelegatingWebMvcConfiguration代码

所以@EnableWebMvc = 集成了DelegatingWebMvcConfiguration =继承了 WebMvcConfigurationSupport


@EnableWebMvc 和@EnableAutoConfiguration的关系

@EnableAutoConfiguration是springboot项目的启动类注解@SpringBootApplication的子元素,主要功能是自动配置。


SpringBoot [WebMvcConfigurationSupport/WebMvcConfigurer]等相关类区别_第3张图片
图3:@SpringBootApplication代码
SpringBoot [WebMvcConfigurationSupport/WebMvcConfigurer]等相关类区别_第4张图片
图4:@EnableAutoConfiguration代码
SpringBoot [WebMvcConfigurationSupport/WebMvcConfigurer]等相关类区别_第5张图片
图5:@AutoConfigurationPackage代码

从上面三张图可以看出,@EnableAutoConfiguration实际是导入了EnableAutoConfigurationImportSelector和Registrar两个类

这两个类的具体原理有些复杂,说不太清楚,主要内容是通过SpringFactoriesLoader.loadFactoryNames()导入jar下面的配置文件META-INF/spring.factories

里面包含了WebMvcAutoConfiguration类(注意:注解是@EnableAutoConfiguration 与类不同),而WebMvcAutoConfiguration 源码如下


SpringBoot [WebMvcConfigurationSupport/WebMvcConfigurer]等相关类区别_第6张图片
图6:WebMvcAutoConfiguration

@ConditionalOnMissingBean({WebMvcConfigurationSupport.class})意思是如果存在它修饰的类的bean,则不需要再创建这个bean。

由此可以得出结论:
如果有额皮质文件继承了DelegatingWebMvcConfiguration或者WebMvcConfigurationSupport,或者配置文件有@EnableWebMvc(该注解只是import了DelegatingWebMvcConfiguration),那么@SpringbootApplication注解中的@EnableAutoConfiguration注解使用的WebMvcAutoConfiguration将不会被自动配置,而是使用WebMvcConfigurationSupport的配置


@EnableWebMvc,WebMvcConfigurationSupport,WebMvcConfigurer和WebMvcConfigurationAdapter使用

WebMvcConfigurationAdapter已经废弃,最好用implements WebMvcConfigurer代替

如果使用继承,WebMvcConfigurationSupport,DelegatingWebMvcConfiguration,或者使用@EnableWebMvc,需要注意会覆盖application.properties中关于WebMvcAutoConfiguration的设置,需要在自定义配置中实现。


总结

implements WebMvcConfigurer : 不会覆盖@EnableAutoConfiguration关于WebMvcAutoConfiguration的配置
@EnableWebMvc + implements WebMvcConfigurer : 会覆盖@EnableAutoConfiguration关于WebMvcAutoConfiguration的配置
extends WebMvcConfigurationSupport :会覆盖@EnableAutoConfiguration关于WebMvcAutoConfiguration的配置
extends DelegatingWebMvcConfiguration :会覆盖@EnableAutoConfiguration关于WebMvcAutoConfiguration的配置

你可能感兴趣的:(SpringBoot [WebMvcConfigurationSupport/WebMvcConfigurer]等相关类区别)