酷代码 AI
菜单
服务商

WebMvcConfigurer和WebMvcConfigurerAdapter的区别

`WebMvcConfigurer`和`WebMvcConfigurerAdapter`都和Spring MVC配置相关,不过存在诸多不同。 历史版本差异 `WebMvcConfigurerAdapter`在Spring 3.2被引入,作为一个抽象类,它实现了`WebMvcConfigurer`接口,该类包含`WebMvcConfigurer`接口所有方法的空实现。这使得开发者在需要自定义Spring MVC配置时,不必实现`WebMvcConfigurer`接口的所有方法,只需要继承`WebMvcConfigurerAdapter`并按需重写方法即可。 而`WebMvcConfigurer`是一个接口,从Spring 5.0开始,`WebMvcConfigurerAdapter`被标记为过时,推荐直接实现`WebMvcConfigurer`接口。这是因为Java 8引入了默认方法,使得接口可以有方法的默认实现,`WebMvcConfigurer`接口中定义了许多默认方法,这样开发者实现该接口时,无需实现其所有方法,按需重写默认方法就行。 使用方式差异 使用`WebMvcConfigurerAdapter`时,需要创建一个类继承`WebMvcConfigurerAdapter`,并重写需要的方法。示例代码如下: ```java import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; // 注意:在Spring 5.0及以后版本,该类已过时 @Deprecated public class MyWebMvcConfigurer extends WebMvcConfigurerAdapter { @Override public void addViewControllers(ViewControllerRegistry registry) { registry.addViewController("/home").setViewName("home"); } } ``` 使用`WebMvcConfigurer`时,需要创建一个类实现`WebMvcConfigurer`接口,并重写需要的方法。示例代码如下: ```java import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration public class MyWebMvcConfig implements WebMvcConfigurer { @Override public void addViewControllers(ViewControllerRegistry registry) { registry.addViewController("/home").setViewName("home"); } } ``` `WebMvcConfigurerAdapter`是早期为方便开发者自定义Spring MVC配置而提供的抽象类,随着Java 8默认方法的引入,`WebMvcConfigurer`接口本身就能满足开发者按需重写方法的需求,所以`WebMvcConfigurerAdapter`被标记为过时,推荐使用`WebMvcConfigurer`接口进行Spring MVC的自定义配置。 [2025-09-17 11:19:00 | AI问答 | 569点数解答]

请收藏新域名:pdcd.cn
发财导航,免费问AI
实用工具查看更多
今日油价 [生活类]
图片互转base64 [开发类]
时间转换器 [开发类]
数独游戏 [娱乐类]
经典推箱子 [娱乐类]
AI摸鱼五子棋 [娱乐类]