WebMvcConfigurer 与 WebMvcConfigurationSupport 全面解析
一、概念介绍
1. WebMvcConfigurer(接口)
用于扩展 Spring MVC 配置,Spring Boot 推荐使用的方式,不会干扰自动配置。
@Configuration
public class MyWebMvcConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new MyInterceptor()).addPathPatterns("/**");
}
}
常用方法:
addInterceptors
addResourceHandlers
configureMessageConverters
addCorsMappings
addViewControllers
configureViewResolvers
2. WebMvcConfigurationSupport(抽象类)
Spring MVC 配置类的父类,继承后等价于 @EnableWebMvc
,会关闭 Spring Boot 自动配置,需要开发者全权管理。
@Configuration
public class MyWebMvcConfig extends WebMvcConfigurationSupport {
@Override
protected void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new MyInterceptor()).addPathPatterns("/**");
}
}
二、区别对比
对比项 | WebMvcConfigurer | WebMvcConfigurationSupport |
---|---|---|
类型 | 接口 | 抽象类 |
推荐程度 | ✅ 推荐 | ❌ 谨慎使用 |
是否保留 Spring Boot 自动配置 | ✅ 是 | ❌ 否 |
是否等价于 @EnableWebMvc | 否 | 是 |
是否能共存多个 | 可以 | 只能继承一个 |
扩展方式 | 增量扩展 | 全量接管 |
影响 | 不影响默认行为 | 会影响静态资源、Swagger 页面等 |
三、源码机制简析
WebMvcConfigurer
由 Spring Boot 自动配置类 WebMvcAutoConfiguration
收集所有 WebMvcConfigurer
并组合成一个:
@Bean
public WebMvcConfigurer compositeWebMvcConfigurer() {
WebMvcConfigurerComposite composite = new WebMvcConfigurerComposite();
composite.addWebMvcConfigurers(this.configurers);
return composite;
}
WebMvcConfigurationSupport
是 Spring MVC 配置的核心类,提供 DispatcherServlet、HandlerMapping、ViewResolver 等组件的默认实现。
一旦继承它,就需要:
- 手动配置静态资源
- 手动配置 Swagger 页面资源
- 手动注册视图解析器等
四、实际开发建议
需求 | 推荐方式 | 原因 |
---|---|---|
扩展拦截器、跨域、静态资源等 | ✅ WebMvcConfigurer | 增量式、不会影响默认行为 |
需要完全接管 Spring MVC 行为 | ⚠️ WebMvcConfigurationSupport | 全量接管,需手动补充很多配置 |
Swagger 页面无法访问、静态资源 404 | 检查是否继承了 WebMvcConfigurationSupport | 需手动注册资源映射 |
五、静态资源配置补充
若使用 WebMvcConfigurationSupport
,需手动注册静态资源路径:
@Override
protected void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/**")
.addResourceLocations("classpath:/static/");
}
六、总结
- ✅ 推荐使用
WebMvcConfigurer
:保留 Spring Boot 默认配置,扩展灵活。 - ❗ 慎用
WebMvcConfigurationSupport
:全量接管 Spring MVC,适用于特殊场景如框架开发。