Spring Boot 与 Spring MVC 的整合并非新增功能,而是 Spring Boot 基于约定大于配置的思想,对 Spring MVC 核心组件实现了开箱即用的自动配置。其本质是通过 spring-boot-starter-web 启动器封装 Spring MVC 核心依赖和自动配置类,让开发者无需手动配置 DispatcherServlet、视图解析器、消息转换器等核心组件,能直接快速使用 Spring MVC 的所有核心能力,同时仍保留完全的自定义扩展能力。

Springboot 官方文档对整合 SpringMVC 的介绍内容链接是
https://docs.spring.io/spring-boot/docs/2.0.2.RELEASE/reference/htmlsingle/#boot-features-spring-mvc
内容如图:

在这里插入图片描述

Spring MVC 自动管理

在 pom.xml 中引入 spring-boot-starter-web 启动器

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

这个启动器不仅封装了 Spring MVC 核心依赖,还包含了内嵌 Tomcat、JSON 解析、Servlet 等依赖,是自动装配的依赖基础

开启自动装配开关

@SpringBootApplication
public class MvcDemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(MvcDemoApplication.class, args);
    }
}

启动类上的 @SpringBootApplication 注解包含 @EnableAutoConfiguration 注解,这个注解会触发 Spring Boot 扫描并加载所有预设的自动配置类

Spring Boot 对 Spring MVC 的自动装配核心由 org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration 类实现

在这里插入图片描述

WebMvcAutoConfiguration 类

在这里插入图片描述

这是典型的条件化配置:仅当应用为 Servlet 类型的 Web 应用、项目引入 Spring MVC 核心依赖,且用户未自定义 WebMvcConfigurationSupport 类(即未完全接管 MVC 底层配置)时,该配置类才会生效。且生效时,它会先等待 DispatcherServlet 和参数校验的自动配置类加载完成,再以高优先级加载自身,确保 Spring MVC 核心组件的自动注册安全且有序。

自动装配的核心内容

WebMvcAutoConfiguration 类会自动向 Spring 容器注册 / 初始化 Spring MVC 核心组件,覆盖请求处理全流程

视图解析器

在这里插入图片描述

自动整合容器中所有的视图解析器

解析视图:

在这里插入图片描述

从容器中获取所有的视图解析器:

在这里插入图片描述

静态资源访问
我的这一篇博客详细讲述了springboot的静态资源映射规则 springboot的热部署和静态资源映射规则

消息转换和格式化

Formatter 格式化器
日期格式化:

在这里插入图片描述

添加格式化器:

在这里插入图片描述

自己添加的格式化转换器只需放在容器中即可

HttpMessageConverters 消息转化器

在这里插入图片描述

从容器中获取所有的 HttpMessageConverters

核心配置项

Spring Boot 提供的核心配置项是简化 Spring MVC 配置的高效捷径。
其本质在于将 Spring MVC 底层繁杂的配置逻辑封装为可直接配置的属性项,开发人员只需根据实际业务场景的需求调整这些配置项的取值,即可快速适配各类业务场景,无需编写复杂的底层配置代码。

举例:把静态资源访问路径从默认的 /** 改成 /static/**,主配置文件 application.yml 中添加如下内容

在这里插入图片描述

扩展 Spring MVC

若核心配置项无法满足定制需求,可通过实现 WebMvcConfigurer 接口进行编程式配置。
在 Spring Boot 中,扩展 Spring MVC 的核心是实现 WebMvcConfigurer 接口,作为 Spring 原生提供的功能扩展接口,它支持在保留 Spring Boot 自动配置的前提下,按需定制 Spring MVC 的各类核心功能,如拦截器、静态资源规则、视图解析器等。

WebMvcConfigurer 接口源码如下:

在这里插入图片描述

编程式配置扩展 Spring MVC 的核心原则:
配置类上必须加 @Configuration 注解,声明为配置类;
配置类上不能加 @EnableWebMvc 注解(否则会禁用 SpringBoot 的 MVC 自动配置,所有组件需手动配置);
扩展逻辑通过重写 WebMvcConfigurer 的默认方法实现,Spring Boot 会自动识别并整合这些配置。

在容器中注册视图控制器

示例:创建一个 MyMVCConfig 实现 WebMvcConfigurer 接口,实现 addViewControllers 方法,完成通过 /login 访问转发到 success.html 的工作,代码如下:

@Configuration
public class MyMVCCofnig implements WebMvcConfigurer{
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/login").setViewName("success");
    }
}

自定义静态资源路径

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
    registry.addResourceHandler("/static/**")
            .addResourceLocations("classpath:/my-static/");
}

例如访问 http://localhost:8080/static/test.js ,会映射到 classpath:/my-static/test.js

注册格式化器

注册格式化器用于解决前端日期字符串与后端 Date 类型参数自动绑定问题,当然通过 application.properties 配置方式也可以实现。

@Override
public void addFormatters(FormatterRegistry registry) {
    registry.addFormatter(new Formatter<Date>() {
        @Override
        public String print(Date date, Locale locale) {
            return null;
        }
        @Override
        public Date parse(String s, Locale locale) throws ParseException {
            return new SimpleDateFormat("yyyy-MM-dd").parse(s);
        }
    });
}

举例实现效果:
当前端通过表单 / JSON 传入 {“createTime”: “2025-12-03”},后端 Controller 方法参数为 public void add(@RequestParam Date createTime),Spring 会自动调用上面注册的 Formatter,将 String 类型的 2025-12-03 解析为 Date 对象。

消息转换器扩展fastjson

在 pom.xml 中引入 fastjson

<dependency>
   <groupId>com.alibaba</groupId>
   <artifactId>fastjson</artifactId>
   <version>1.2.47</version>
</dependency>

配置消息转换器

添加 fastjson,Spring 集成 fastjson 处理 JSON 转换的全局配置

@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
    FastJsonHttpMessageConverter fc = new FastJsonHttpMessageConverter();
    FastJsonConfig fastJsonConfig = new FastJsonConfig();
    fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat);
    fc.setFastJsonConfig(fastJsonConfig);
    converters.add(fc);
}

当这个配置生效后,Spring MVC 的 JSON 处理会完全交给 fastjson,返回的 JSON 会是格式化后的结构

在实体类上可以继续控制,使用 @JSONField 注解,此注解是对全局配置的局部覆盖

public class User{
    @JSONField(format = "yyyy-MM-dd")
    private Date date;
}

指定 date 字段在 JSON 序列化(Java 对象 → JSON 字符串)和反序列化(JSON 字符串 → Java 对象)时的日期格式。

拦截器

创建拦截器

public class MyInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("前置拦截");
        return true;
    }
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("后置拦截");
    }
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("最终拦截");
    }
}

拦截器注册

@Override
public void addInterceptors(InterceptorRegistry registry) {
    registry.addInterceptor(new MyInterceptor())
            .addPathPatterns("/**")
            .excludePathPatterns("/hello2");
}

addPathPatterns:指定拦截的路径(支持通配符);
excludePathPatterns:指定排除的路径(必须包含静态资源、错误页面等,否则会拦截这些默认资源)。

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐