WebMvcConfigurationSupport 和WebMvcConfigurationAdapter的区别

今天看项目的代码的时候发现了一个有趣的事情,一个为了解决跨域问题的配置类

//@Configuration
public class CorsConfigure extends WebMvcConfigurationSupport

我发现继承的是
WebMvcConfigurationSupport,然后我看网上对于跨域问题的解决配置类中继承的都是WebMvcConfigurationAdapter  

我就觉得很奇怪,就去百度了一下他们的差别,现在记录一下

1.@EnableWebMvc+extends WebMvcConfigurationAdapter,在扩展的类中重写父类的方法即可,这种方式会屏蔽springboot的@EnableAutoConfiguration中的设置
2.extends WebMvcConfigurationSupport,在扩展的类中重写父类的方法即可,这种方式会屏蔽springboot的@EnableAutoConfiguration中的设置
3.extends WebMvcConfigurationAdapter,在扩展的类中重写父类的方法即可,这种方式依旧使用springboot的@EnableAutoConfiguration中的设置

至于为什么会屏蔽@EnableAutoConfiguration的设置,这要看@EnableAutoConfiguration到底做了什么,springMvc在boot完成自动装配相关的类:WebMvcAutoConfiguration

@Configuration
@ConditionalOnWebApplication(type = Type.SERVLET)
@ConditionalOnClass({ Servlet.class, DispatcherServlet.class, WebMvcConfigurer.class })
@ConditionalOnMissingBean(WebMvcConfigurationSupport.class)
@AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE + 10)
@AutoConfigureAfter({ DispatcherServletAutoConfiguration.class,
ValidationAutoConfiguration.class })
public class WebMvcAutoConfiguration 

可以看到一旦boot中一旦出现WebMvcConfigurationSupport类的话,这个自动装配的类就不会出现了,这就是上述1,2表述的原因

另外现在WebMvcConfigurationAdapter已经被WebMvcConfigurer代替

至于3,比较复杂,想要深入了解可以参考原文

注意:经过我实践发现,在springboot项目中 一旦写了一个配置类  继承WebMvcConfigurationSupport 之后  再写一个类 实现  WebMvcConfigurer 就没有效果了!但是一旦在boot项目中,加上@EnableAWebMvc之后,

继承WebMvcConfigurationSupport 的类就失效了,实现  WebMvcConfigurer 的类就起作用了

也就是说 使用 implement WebMvcConfigurer 会在支持原有默认配置的情况下 新增配置  一旦加入@EnableWebMvc相当于引入了WebMvcConfigurationSupport 就会屏蔽掉默认的配置


参考
原文:https://blog.csdn.net/lqadam/article/details/80637335




原文地址:https://www.cnblogs.com/changeCode/p/10938640.html