前言
今天用Sping Boot2.0.3写项目编写WebMvc的JavaConfig时,发现WebMvcConfigurerAdapter已经被标注弃用,便去找了下Spring的API,发现官方开始推荐直接实现WebMvcConfigurer接口的方式来配置SpringMVC。(原因在Java8接口默认方法替代了原来适配器的作用)🖊
在SpringBoot2.0及Spring 5.0 WebMvcConfigurerAdapter已被废弃,目前找到解决方案就有两种
1. 直接实现WebMvcConfigurer (官方推荐)
1 |
|
2. 直接继承WebMvcConfigurationSupport
1 |
|
WebMvcConfigurerAdapter的官方api描述
WebMvcConfigurerAdapter — Deprecated.
as of 5.0 WebMvcConfigurer has default methods (made possible by a Java 8 baseline) and can be implemented directly without the need for this adapter.
An implementation of WebMvcConfigurer with empty methods allowing subclasses to override only the methods they’re interested in.
Java8中WebMvcConfigurer实现了默认方法,不需要这个适配器了。
因为WebMvcConfigurer接口实现了默认方法,使用者可以自由实现想配置的方法
解释:
在Java8以前,因为实现接口的时候每个接口方法必须需要实现,所以导致编写JavaConfig配置类很困难,不能自由选择配置类,所以Spring5.0以前用一个适配器抽象类实现了WebMvcConfigurer的所有方法(但其实都是空的),这样可以满足用户可以选择自己需要的配置功能进行选择性配置,而不需要全部实现。
而现在Java8提供了接口默认实现方法,接口的默认方法完全替代了这个适配器类的目的,可以满足仅在接口层面用户就能选择自己想实现的方法,没有实现的方法就用默认方法代替,原来的适配器就多余了。因此推荐第一种方式。