SpringBoot中WebMvcConfigurationSupport与WebMvcConfigurer

 

接上一篇:SpringBoot自动配置原理,SpringBoot也对SpringMVC做了自动配置,先看一下WebMvc的自动配置类

发现了标题提到的两位主角,很明显,有WebMvcConfigurer存在时,WebMvc的自动配置才能生效,如果有WebMvcConfigurationSupport那就不生效了。

Spring Boot 2.0后用自己的的配置类继承WebMvcConfigurerAdapter时,idea会提示这个类已经过时了。通常情况下我们会采用下面两种代替方案:

  • 实现WebMvcConfigurer  
  • 继承WebMvcConfigurationSupport

如果 WebMvcAutoConfiguration不生效会导致以下几个问题:

  1. WebMvcProperties 和 ResourceProperties 失效

因为两个配置类中的属性都在 WebMvcAutoConfiguration中使用。当WebMvc自动配置失效(WebMvcAutoConfiguration自动化配置)时,会导致无法视图解析器无法解析并返回到对应的视图。

解决办法:可以实现WebMvcConfigurer并重写相关方法来达到类似的功能。

扩展

@EnableWebMvc  该注解会关闭默认配置
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE})
@Documented
@Import({DelegatingWebMvcConfiguration.class})
public @interface EnableWebMvc {
}

DelegatingWebMvcConfiguration这个类是继承了WebMvcConfigurationSupport的,这就是它为什么可以关闭默认配置的原因了。

① 你希望关闭默认配置,自己完全重新实现一个

@EnableWebMvc
@Configuration
public class WebConfig implements WebMvcConfigurer {

② 你希望重写部分配置

//@EnableWebMvc
@Configuration
public class WebConfig implements WebMvcConfigurer {

或者

@EnableWebMvc
@Configuration
public class WebConfig extends WebMvcAutoConfiguration {

 


版权声明:本文为QingXu1234原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。