• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

详解Spring Boot中如何自定义SpringMVC配置

springboot 搞代码 4年前 (2022-01-09) 22次浏览 已收录 0个评论
文章目录[隐藏]

前言

在 Spring Boot 框架中只需要在项目中引入 spring-boot-starter-web 依赖,SpringMVC 的一整套东西就会自动给我们配置好;但是,真实的项目环境比较复杂,系统自带的配置不一定满足我们的需求,往往我们还需要结合实际情况自定义配置。
自定义配置就有讲究了,由于 Spring Boot 的版本变迁,加上这一块本身就有几个不同写法,容易搞混。

一、SpringBoot 中 SpringMVC 配置概述

首先我们需要明确,跟自定义 SpringMVC 相关的类和注解主要有如下四个:

  • WebMvcConfigurerAdapter
  • WebMvcConfigurer
  • WebMvcConfigurationSupport
  • @EnableWebMvc

这四个中,除了 @EnableWebMvc 是注解外,WebMvcConfigurerAdapter 和 WebMvcConfigurationSupport 是两个类,WebMvcConfigurer 是一个接口。里边的方法看起来好像都类似,但是实际使用效果却大不相同。

二、WebMvcConfigurerAdapter 抽象类

我们先来看 WebMvcConfigurerAdapter,这个是在 Spring Boot 1.x 中我们自定义 SpringMVC 时继承的一个抽象类。
这个抽象类本身是实现了 WebMvcConfigurer 接口,然后抽象类里边都是空方法,我们来看一下这个类的声明:

public abstract class WebMvcConfigurerAdapter implements WebMvcConfigurer {
    //各种 SpringMVC 配置的方法
}

再来看看这个类的注释:

/**
 * An implementation of {@link WebMvcConfigurer} with empty methods allowing
 * subclasses to override only the methods they're interested <a>本文来源gao($daima.com搞@代@#码(网</a>in.
 * @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
 */

这段注释关于这个类说的很明白了。

同时我们也看到,从 Spring5 开始,由于我们要使用 Java8,而 Java8 中的接口允许存在 default 方法,因此官方建议我们直接实现 WebMvcConfigurer 接口,而不是继承 WebMvcConfigurerAdapter。

也就是说,在 Spring Boot 1.x 的时代,如果我们需要自定义 SpringMVC 配置,直接继承 WebMvcConfigurerAdapter 类即可。

三、WebMvcConfigurer 接口

如上所述,WebMvcConfigurer 是在 Spring Boot 2.x 中实现自定义配置的方案。

WebMvcConfigurer 是一个接口;接口中的方法和 WebMvcConfigurerAdapter 中定义的空方法其实一样,所以用法上来说,基本上没有差别。

从 Spring Boot 1.x 切换到 Spring Boot 2.x ,只需要把继承类改成实现接口即可。

四、WebMvcConfigurationSupport 类-自定义配置

在 Spring 框架中,可以通过 Spring 和 SpringMVC 的XML 配置文件设置MVC 框架;在 Spring Boot 中自定义 SpringMVC 配置时,可以通过继承 WebMvcConfigurationSupport 类来实现。


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:详解Spring Boot中如何自定义SpringMVC配置
喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址