自定义WebmvcConfigurer能实现管理什么
在 Spring
框架中,WebMvcConfigurer
接口是一个非常重要的配置接口,它允许开发者通过自定义配置来扩展和定制
Spring MVC
的默认行为。通过实现WebMvcConfigurer
接口(或继承WebMvcConfigurationSupport
类),可以对
Spring MVC 的多个核心功能进行灵活配置。
以下是自定义WebMvcConfigurer
能实现的主要功能及详细说明:
请求映射与处理器配置
自定义处理器映射(HandlerMapping)和适配器(HandlerAdapter)
- 可以注册自定义的
HandlerMapping
(如基于注解的RequestMappingHandlerMapping
)或HandlerAdapter
(如RequestMappingHandlerAdapter
),用于处理不同类型的请求映射逻辑。 - 场景:自定义 URL 匹配规则、处理特殊请求格式(如 RESTful API 版本控制)。
- 可以注册自定义的
静态资源处理
配置静态资源(如 HTML、CSS、JS、图片等)的访问路径和缓存策略:
1
2
3
4
5
6
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/static/**")
.addResourceLocations("classpath:/static/")
.setCachePeriod(3600); // 缓存1小时
}场景:将静态资源映射到类路径、文件系统路径或 CDN 地址。
视图与数据格式化
视图解析器配置
注册自定义视图解析器(如 Thymeleaf、FreeMarker、JSP 等),或修改默认视图解析规则:
1
2
3
4
public void configureViewResolvers(ViewResolverRegistry registry) {
registry.jsp("/WEB-INF/views/", ".jsp"); // JSP视图解析器
}场景:使用模板引擎时配置视图前缀、后缀或自定义视图解析逻辑。
数据格式化与转换
注册自定义的
Converter
(类型转换器)和Formatter
(格式化器),处理请求参数和响应结果的类型转换:1
2
3
4
public void addFormatters(FormatterRegistry registry) {
registry.addConverter(String.class, LocalDate.class, new StringToLocalDateConverter());
}场景:将字符串参数自动转换为
LocalDate
、Enum
等类型,或格式化日期、数字等响应数据。
拦截器与请求处理
拦截器注册
配置拦截器(
HandlerInterceptor
),用于预处理请求或后处理响应:1
2
3
4
5
6
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new LoginInterceptor())
.addPathPatterns("/api/**") // 拦截路径
.excludePathPatterns("/api/public/**"); // 排除路径
}场景:实现登录认证、请求日志记录、性能监控等功能。
跨域请求处理(CORS)
- 配置跨域资源共享(CORS)规则,允许前端跨域访问后端 API:
1
2
3
4
5
6
7
8
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/api/**")
.allowedOrigins("https://example.com")
.allowedMethods("GET", "POST", "PUT", "DELETE")
.allowedHeaders("*")
.maxAge(3600);
}- 场景:前后端分离项目中解决跨域访问限制。
请求处理与参数配置
请求参数处理
配置
RequestBody
和RequestParam
的解析规则,如设置 JSON 解析器(Jackson)、表单解析器等:1
2
3
4
5
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
// 添加自定义JSON转换器
converters.add(new MappingJackson2HttpMessageConverter(objectMapper));
}场景:自定义请求体解析(如处理特殊格式的 JSON、XML)或响应数据序列化规则
异步请求处理
配置异步请求处理(如
DeferredResult
、WebSocket)的相关参数:1
2
3
4
5
public void configureAsyncSupport(AsyncSupportConfigurer configurer) {
configurer.setDefaultTimeout(30000); // 异步请求超时时间
configurer.registerCallableInterceptors(new TimeoutCallableInterceptor());
}场景:实现长轮询、WebSocket 通信等异步业务场景。
RESTful API 特性增强
内容协商(Content Negotiation)
配置不同请求 Accept 头对应的响应格式(如 JSON、XML、HTML)
1
2
3
4
5
6
7
public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
configurer.favorPathExtension(true) // 基于URL后缀(.json/.xml)
.favorParameter(true) // 基于参数(?format=json)
.parameterName("format")
.defaultContentType(MediaType.APPLICATION_JSON);
}场景:根据客户端请求头返回不同格式的数据,提升 API 兼容性。
HTTP 消息转换器
自定义
HttpMessageConverter
,处理请求和响应的消息转换(如添加 Protobuf、CSV 支持):1
2
3
4
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
converters.add(new ProtobufHttpMessageConverter());
}
其他功能扩展
- 异常处理配置
- 注册全局异常处理器(
@ControllerAdvice
+@ExceptionHandler
),或通过WebMvcConfigurer
间接配置: - 场景:统一处理 API 异常,返回标准化错误响应。
- 注册全局异常处理器(
- 默认 Servlet 处理
- 配置 Spring MVC 对默认 Servlet(如 Tomcat 的默认 Servlet)的处理策略:
- 场景:处理静态资源请求时,若 Spring MVC 未匹配到对应处理器,交由容器默认 Servlet 处理。
自定义 WebMvcConfigurer
配置类的三种自定义方式
全自动 | 直接编写控制器逻辑 | 全部使用自动配置默认效果 | |
---|---|---|---|
手自一体 | @Configuration + 配置 WebMvcConfigurer +
配置 WebMvcRegistrations |
不要标注@EnableWebMvc |
自动配置效果 手动设置部分功能 定义 MVC 底层组件 |
全手动 | @Configuration + 配置
WebMvcConfigurer |
标注@EnableWebMvc |
禁用自动配置效果 全手动设置 |
总结:所有的自定义模式,给容器类放一个配置类
@Configuration
实现
WebMvcConfigurer
,不要标注@EnableWebMvc
注解,实现了手自一体的模式。
一些问题
@EnableWebMvc
的影响- 若配置类添加
@EnableWebMvc
,会完全覆盖 Spring MVC 的自动配置(如默认视图解析器、消息转换器等),需手动配置所有需要的功能。 - 若仅需扩展部分功能,建议不添加
@EnableWebMvc
,保持 Spring Boot 的自动配置。
- 若配置类添加
- 优先级与顺序
- 多个
WebMvcConfigurer
实现类的配置会合并生效,可通过@Order
注解控制优先级。
- 多个
- 与
WebMvcConfigurationSupport
的区别WebMvcConfigurationSupport
是一个基类,提供更底层的配置能力,但会完全禁用 Spring Boot 的自动配置;WebMvcConfigurer
接口则更轻量级,用于扩展而非覆盖默认配置,推荐优先使用。
自定义配置类实现 WebMvcConfigurer 接口
容器中只要有 一个 WebMvcConfigurer 组件,就能自定义底层,配置的底层行为都会生效
路径和缓存配置,手自一体模式
1 | // 告诉 Spring 这是一个配置类,给容器中放一个 WebMvcConfigurer 组件,就能自定义底层 |
或者,第二种模式
1 | // 告诉 Spring 这是一个配置类 |

一个比较完整的自定义配置类实现 WebMvcConfigurer 接口
1 | package edu.software.ergoutree.springbootwebpart1.config; |
为什么我们容器中放一个 WebMvcConfigurer 就能配置底层行为
Spring
MVC的配置机制是一个典型的”组合模式”应用,通过WebMvcConfigurer
接口提供了一种灵活的方式来定制MVC行为。
其中的核心组件关系如下
1 | [WebMvcAutoConfiguration] |
自动配置入口 是 WebMvcAutoConfiguration
,Spring Boot
的自动配置类WebMvcAutoConfiguration
是整个过程的总入口
在 public class WebMvcAutoConfiguration
自动配置类中,有这么两个类WebMvcAutoConfigurationAdapter
和EnableWebMvcConfiguration
WebMvcAutoConfigurationAdapter
有一个 WebMvcAutoConfigurationAdapter
类,这个类是Spring
Boot 早期版本中用于自动配置 Spring MVC
的一个适配器类,主要功能是在不覆盖自动配置的前提下,允许开发者通过继承该类来扩展或自定义
Spring MVC
的配置。所以说,自动配置入口中会有这个类来支持用户自定义自动配置的内容。
这个类中的配置最先执行(Order=0),其他自定义WebMvcConfigurer
按@Order
注解顺序执行
1 |
|
其中:
@Import(EnableWebMvcConfiguration.class)
引入了核心配置WebMvcAutoConfigurationAdapter
本身也是一个WebMvcConfigurer
实现
EnableWebMvcConfiguration
EnableWebMvcConfiguration
这个类,继承了DelegatingWebMvcConfiguration
类,这两个类都生效
这个类主要功能就是在 @EnableWebMvc
注解被启用时发挥作用,而WebMvcAutoConfiguration
是 Spring
Boot 自动配置 MVC 的主类,在未启用 @EnableWebMvc
时生效
所以说,这个类是WebMvcAutoConfiguration
支持全手动配置的一个重要入口类
1 |
|
而且还继承了DelegatingWebMvcConfiguration
类,这个类是配置委托链
DelegatingWebMvcConfiguration
EnableWebMvcConfiguration
继承了DelegatingWebMvcConfiguration
,这是整个机制的核心,作为
@EnableWebMvc
注解的实际载体,负责收集并应用所有实现了
WebMvcConfigurer
接口的配置类。
而且DelegatingWebMvcConfiguration
还继承自
WebMvcConfigurationSupport
(Spring MVC
的基础配置类),并在其基础上实现了配置的委派机制。
源码中有一段这个利用IoC和DI
,把容器中所有的WebMvcConfigurer
的 Bean
注入进来,实现将开发者自定义的配置与 Spring MVC 的默认配置进行整合。
在 WebMvcConfigurationSupport
的基础上,DelegatingWebMvcConfiguration
将关键配置方法的实现委托给收集到的 WebMvcConfigurer
之后,WebMvcConfigurerComposite
类负责按顺序执行所有配置器的方法:
1 | public class DelegatingWebMvcConfiguration extends WebMvcConfigurationSupport { |
- 自动装配所有WebMvcConfigurer:通过
@Autowired
注入容器中所有WebMvcConfigurer
实现 - 委托模式:将配置工作委托给
WebMvcConfigurerComposite
- 方法覆盖:重写父类
WebMvcConfigurationSupport
的所有配置方法
别人调用
DelegatingWebMvcConfiguration
类的方法配置底层规则,而它调用所有的WebMvcConfigurer
的配置底层方法,这个类将工作委托给组合对象
当应用中添加 @EnableWebMvc
注解时,Spring 会导入
DelegatingWebMvcConfiguration
,然后 Spring 扫描容器中的所有
Bean,找出实现了 WebMvcConfigurer
接口的类,将这些配置器注入到 DelegatingWebMvcConfiguration
的 configurers
字段中。
WebMvcConfigurerComposite
还有一个配置聚合器,WebMvcConfigurerComposite
是实际处理多个配置器的核心类,通过WebMvcConfigurerComposite
统一处理多个配置器
1 | class WebMvcConfigurerComposite implements WebMvcConfigurer { |
- 收集所有
WebMvcConfigurer
实例 - 遍历调用每个配置器的对应方法
- 保证所有自定义配置都能生效
流程分析
所以说,当Spring MVC初始化时,完整的调用链如下:
DispatcherServlet
初始化触发MVC配置WebMvcConfigurationSupport
中的配置方法被调用DelegatingWebMvcConfiguration
重写的方法被执行WebMvcConfigurerComposite
遍历所有WebMvcConfigurer
- 最终执行到开发者自定义的配置逻辑
配置生效过程也就是
- Spring容器初始化时发现
MyWebMvcConfig
DelegatingWebMvcConfiguration
通过@Autowired
收集到该配置器- MVC初始化时调用
configurePathMatch
方法 WebMvcConfigurerComposite
遍历调用所有配置器的该方法- 最终
PathMatchConfigurer
被配置为不使用尾部斜杠匹配
WebMvcConfigurer
的源码回顾
这里是 WebMvcConfigurer
这个接口的源码,提供了配置
Spring MVC 底层的所有组件入口
1 | // WebMvcConfigurer接口用于对Spring MVC进行自定义配置 |