Spring Boot 中自定义 SpringMVC 配置,到底继承谁?

本文探讨了在Spring Boot中自定义SpringMVC配置的最佳实践。Spring Boot 1.x推荐继承WebMvcConfigurerAdapter,而从2.x开始,官方建议直接实现WebMvcConfigurer接口。WebMvcConfigurationSupport通常用于非Spring Boot的Java配置SSM项目,继承它可能导致Spring Boot的自动化配置失效。避免使用@EnableWebMvc注解,因为它会禁用默认的SpringMVC配置。
摘要由CSDN通过智能技术生成

public abstract class WebMvcConfigurerAdapter implements WebMvcConfigurer {

//各种 SpringMVC 配置的方法

}

再来看看这个类的注释:

/**

  • An implementation of {@link WebMvcConfigurer} with empty methods allowing

  • subclasses to override only the methods they’re interested in.

  • @deprecated as of 5.0 {@link WebMvcConfigurer} has default methods (made

  • possible by a Java 8 baseline) and can be implemented directly without the

  • need for this adapter

*/

这段注释关于这个类说的很明白了。同时我们也看到,从 Spring5 开始,由于我们要使用 Java8,而 Java8 中的接口允许存在 default 方法,因此官方建议我们直接实现 WebMvcConfigurer 接口,而不是继承 WebMvcConfigurerAdapter 。

也就是说,在 Spring Boot 1.x 的时代,如果我们需要自定义 SpringMVC 配置,直接继承 WebMvcConfigurerAdapter 类即可。

WebMvcConfigurer


根据上一小节的解释,小伙伴们已经明白了,WebMvcConfigurer 是我们在 Spring Boot 2.x 中实现自定义配置的方案。

WebMvcConfigurer 是一个接口,接口中的方法和 WebMvcConfigurerAdapter 中定义的空方法其实一样,所以用法上来说,基本上没有差别,从 Spring Boot 1.x 切换到 Spring Boot 2.x ,只需要把继承类改成实现接口即可。

松哥在之前的案例中(40 篇原创干货,带你进入 Spring Boot 殿堂!),凡是涉及到自定义 SpringMVC 配置的地方,也都是通过实现 WebMvcConfigurer 接口来完成的。

WebMvcConfigurationSupport


前面两个都好理解&#

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值