SpringMVC WebMvcConfigurerAdapter已过时的解决方法

Spring5.0之前,拦截器配置都是直接继承WebMvcConfigurerAdapter的,从5.0之后,这个类已废弃,源码中注释如下:

/**
* An implementation of {@link WebMvcConfigurer} with empty methods allowing
* subclasses to override only the methods they're interested in.
*
* @author Rossen Stoyanchev
* @since 3.1
* @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
*/

大致意思是:拜Java 8所赐,WebMvcConfigurer有了defalut方法,允许子类仅覆盖那些需要的方法,所以这个适配器不需要了,直接继承WebMvcConfigurer接口就好了。

通过查看WebMvcConfigurer源码,发现方法都已经改成了defalut修饰,并且两个nullable方法也迁移过来了:

SpringMVC WebMvcConfigurerAdapter已过时的解决方法

看到这两个Nullable方法就明白了,因为在老版本里,接口方法是不能有方法体的,所以才要有WebMvcConfigurerAdapter去包装一下,现在这个return null可以写到接口里了,所以就不用多余再写一个抽象类了。

故新的写法如下:

SpringMVC WebMvcConfigurerAdapter已过时的解决方法