WebMvcConfigurer介绍-笔记
1.WebMvcConfigurer功能简介
org.springframework.web.servlet.config.annotation.WebMvcConfigurer
是 Spring MVC 提供的一个接口,用于自定义 Web 应用的配置。通过实现该接口,开发者可以灵活地添加拦截器(Interceptors)、配置视图解析器、设置静态资源处理规则、定义消息转换器(Message Converters)等,从而对 Spring MVC 的行为进行深度定制。
WebMvcConfigurer
接口提供了一系列默认方法(Default Methods),可以通过重写这些方法来实现自定义配置。
public interface WebMvcConfigurer {default void addInterceptors(InterceptorRegistry registry) {}default void addResourceHandlers(ResourceHandlerRegistry registry) {}default void addCorsMappings(CorsRegistry registry) {}// ......
}
以下是一些常见的功能介绍:
方法 | 用途 |
---|---|
addInterceptors(InterceptorRegistry registry) | 添加自定义拦截器 |
addViewControllers(ViewControllerRegistry registry) | 添加简单的 URL 到视图的映射 |
configureMessageConverters(List<HttpMessageConverter<?>> converters) | 配置 HTTP 消息转换器 |
addResourceHandlers(ResourceHandlerRegistry registry) | 注册静态资源处理器 |
addCorsMappings(CorsRegistry registry) | 配置跨域请求 |
configurePathMatch(PathMatchConfigurer configurer) | 配置路径匹配规则 |
addFormatters(FormatterRegistry registry) | 添加格式化器(如日期格式) |
2. 使用示例
要使用 WebMvcConfigurer
,你需要创建一个配置类并实现该接口,通常还需要添加 @Configuration
和 @EnableWebMvc(可选)
注解。
import org.springframework.context.annotation.Configuration;@Configuration
//@EnableWebMvc //可选项,加上该注解后,会启用 Spring MVC 的默认配置,并禁用 Spring Boot 的自动配置。如果只是想微调配置,可以不加这个注解。
public class WebConfig implements WebMvcConfigurer {// 示例:添加自定义拦截器(Interceptor)@Overridepublic void addInterceptors(InterceptorRegistry registry) {//拦截器需要注册到 InterceptorRegistry 中才能生效。registry.addInterceptor(new MyCustomInterceptor()).addPathPatterns("/**");}// 示例:配置视图控制器(ViewController),添加 URL 到视图的映射@Overridepublic void addViewControllers(ViewControllerRegistry registry) {//这样 /home 请求会直接跳转到 home.jsp(或 Thymeleaf 的 home.html)。registry.addViewController("/home").setViewName("home");registry.addViewController("/login").setViewName("login");}//示例:配置消息转换器(Message Converter)@Overridepublic void configureMessageConverters(List<HttpMessageConverter<?>> converters) {//手动添加了 Jackson 的 JSON 转换器converters.add(new MappingJackson2HttpMessageConverter());}// 示例:配置静态资源处理@Overridepublic void addResourceHandlers(ResourceHandlerRegistry registry) {registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");}// 示例:配置跨域请求//假设有如下架构: 前端:http://example.com; 后端 API:http://api.example.com/api/**//下述配置后,浏览器就知道允许 http://example.com 的请求访问 /api/** 路径下的接口,且只允许 GET 和 POST 方法,每次 OPTIONS 请求的结果最多缓存 1 小时@Overridepublic void addCorsMappings(CorsRegistry registry) {registry.addMapping("/api/**") //指定哪些 URL 路径需要启用 CORS 配置;可以配置多个路径.allowedOrigins("http://example.com")//指定允许访问当前 API 的前端来源:这里只有来自 http://example.com 的请求才被允许.allowedMethods("GET", "POST")//指定允许的 HTTP 请求方法//当浏览器第一次发送一个复杂请求(如 PUT 或带有自定义头的请求)时,会先发送一个 OPTIONS 请求(预检请求),询问是否允许该请求。通过设置 maxAge,浏览器会在指定时间内缓存这个结果,避免重复发送 OPTIONS 请求,从而提高性能。.maxAge(3600);//设置浏览器缓存预检请求(Preflight Request)的最长时间(单位:秒)}
}
其中,自定义拦截器(Interceptor)定义如下:
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;public class MyCustomInterceptor implements HandlerInterceptor {@Overridepublic boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {System.out.println("请求前执行:" + request.getRequestURI());return true;}@Overridepublic void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {System.out.println("请求后执行:" + request.getRequestURI());}
}
注意事项:
@EnableWebMvc
会启用 Spring MVC 的默认配置,并禁用 Spring Boot 的自动配置。如果只是想微调配置,可以不加这个注解。- 在 Spring Boot 中,如果使用了
@SpringBootApplication
,默认已经启用了 MVC 配置,无需额外添加@EnableWebMvc
。 - 如果只实现WebMvcConfigurer的部分方法,其他默认配置仍会保留。
总结:WebMvcConfigurer
是 Spring MVC 的强大扩展点,能够让你以非侵入式的方式自定义 Web 应用的行为。通过实现其方法,你可以轻松控制拦截器、视图映射、静态资源、消息转换器等核心组件,是构建企业级 Web 应用不可或缺的工具之一。
如果有具体的需求,比如需要配置跨域、安全权限控制或国际化设置,可以基于这个接口进一步扩展。