一、@EnableWebMvc是什么
直接看源码,@EnableWebMvc实际上引入一个DelegatingWebMvcConfiguration。
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE})
@Documented
@Import({DelegatingWebMvcConfiguration.class})
public @interface EnableWebMvc {
}
DelegatingWebMvcConfiguration继承了WebMvcConfigurationSupport
@Configuration
public class DelegatingWebMvcConfiguration extends WebMvcConfigurationSupport {
...
所以@EnableWebMvc=继承DelegatingWebMvcConfiguration=继承WebMvcConfigurationSupport
二、@EnableWebMvc,WebMvcConfigurationSupport,WebMvcConfigurer和WebMvcConfigurationAdapter使用
WebMvcConfigurationAdapter已经废弃,最好用implements WebMvcConfigurer代替!!!
@Configuration
public class MyConfig implements WebMvcConfigurer {
}
如果使用继承,WebMvcConfigurationSupport,DelegatingWebMvcConfiguration,或者使用@EnableWebMvc,
需要注意会覆盖application.properties中关于WebMvcAutoConfiguration的设置,需要在自定义配置中实现,如:
《springboot2.0、spring5.0 拦截器配置WebMvcConfigurerAdapter过时使用WebMvcConfigurationSupport来代替 新坑》
示例如下
Configuration
@EnableWebMvc
public class MyConfig implements WebMvcConfigurer {
}
@Configuration
public class MyConfig extends WebMvcConfigurationSupport {
}
@Configuration
public class MyConfig extends DelegatingWebMvcConfiguration {
}
上面代码中需要在类中实现关于WebMvcAutoConfiguration的配置,而不是在application.properties中。
三、总结
- implements WebMvcConfigurer : 不会覆盖@EnableAutoConfiguration关于WebMvcAutoConfiguration的配置
- @EnableWebMvc + implements WebMvcConfigurer : 会覆盖@EnableAutoConfiguration关于WebMvcAutoConfiguration的配置
- extends WebMvcConfigurationSupport :会覆盖@EnableAutoConfiguration关于WebMvcAutoConfiguration的配置
- extends DelegatingWebMvcConfiguration :会覆盖@EnableAutoConfiguration关于WebMvcAutoConfiguration的配置