Warning: “The type WebMvcConfigurerAdapter is deprecated” – 警告:“WebMvcConfigurerAdapter的类型已被废弃&#8221。

最后修改: 2018年 6月 18日

1. Introduction


In this quick tutorial, we’ll have a look at one of the warnings we may see when working with a Spring 5.x.x version, namely the one referring to the deprecated WebMvcConfigurerAdapter class.

在这个快速教程中,我们将看看在使用Spring 5.x.x版本时可能看到的警告之一,即提到已废弃的WebMvcConfigurerAdapter类。

We’ll see why this warning happens and how to handle it.


2. Why the Warning Is Present


This warning will appear if we’re using Spring version 5 (or Spring Boot 2), either when upgrading an existing application or building a new application with the old API.

如果我们使用Spring版本5(或Spring Boot 2),无论是升级现有的应用程序还是用旧的API构建新的应用程序,都会出现这个警告

Let’s briefly go through the history behind it.


In earlier versions of Spring, up to and including version 4, if we wanted to configure a web application, we could make use of the WebMvcConfigurerAdapter class:


public WebConfig extends WebMvcConfigurerAdapter {
    // ...

This is an abstract class that implements the WebMvcConfigurer interface and contains empty implementations for all the methods inherited.


By subclassing it, we can override its methods, which provide hooks into various MVC configuration elements such as view resolvers, interceptors and more.


However, Java 8 added the concept of default methods in interfaces. Naturally, the Spring team updated the framework to make full use of the new Java language features.

然而,Java 8增加了接口中默认方法的概念。当然,Spring团队更新了框架,以充分利用新的Java语言特性。

3. Solution


As mentioned, the WebMvcConfigurer interface, starting with Spring 5, contains default implementations for all its methods. As a result, the abstract adapter class was marked as deprecated.

如前所述,从Spring 5开始,WebMvcConfigurer接口包含其所有方法的默认实现。因此,抽象的适配器类被标记为废弃的。

Let’s see how we can start using the interface directly and get rid of the warning:


public WebConfig implements WebMvcConfigurer {
    // ...

And that’s all! The change should be fairly easy to make.


If there are any super() calls to overridden methods, we should remove those as well. Otherwise, we can override any of the configuration callbacks as usual.


While removing the warning is not mandatory, it’s recommended to do so, as the new API is more convenient, and the deprecated class may be removed in future versions.


4. Conclusion


In this short article, we saw how to fix the warning referring to the deprecation of the WebMvcConfigurerAdapter class.