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

最后修改: 2018年 6月 18日

中文/混合/英文(键盘快捷键:t)

1. Introduction

1.绪论

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

2.为什么会出现警告

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:

在Spring的早期版本中,包括第4版在内,如果我们想配置一个Web应用程序,我们可以使用WebMvcConfigurerAdapter类。

@Configuration
public WebConfig extends WebMvcConfigurerAdapter {
    
    // ...
}

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

这是一个实现WebMvcConfigurer接口的抽象类,包含了所有继承的方法的空实现。

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

通过子类化它,我们可以覆盖它的方法,这些方法提供了进入各种MVC配置元素的钩子,如视图解析器、拦截器等等。

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

3.解决办法

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:

让我们看看如何开始直接使用该接口并摆脱警告

@Configuration
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.

如果有任何super()调用被重写的方法,我们也应该删除这些方法。否则,我们可以像往常一样覆盖任何配置回调。

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.

虽然删除警告不是强制性的,但建议这样做,因为新的API更方便,而且在未来的版本中可能会删除这个废弃的类。

4. Conclusion

4.总结

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

在这篇短文中,我们看到了如何修复提及WebMvcConfigurerAdapter类被废弃的警告。