WebMvcConfigurer
?是 Spring MVC 提供的一個擴展接口,用于配置 Spring MVC 的各種功能。在 Spring Boot 應用中,通過實現?WebMvcConfigurer
?接口,可以定制和擴展默認的 Spring MVC 配置。以下是對?WebMvcConfigurer
?的詳細解析及其常見用法。
一、基本概念
WebMvcConfigurer
?接口提供了一組回調方法,用于配置 Spring MVC 的各種方面,如視圖解析器、攔截器、跨域請求、消息轉換器等。通過實現這些方法,可以方便地自定義 MVC 配置。
二、實現 WebMvcConfigurer
-
創建配置類:
在 Spring Boot 應用中,創建一個配置類并實現?WebMvcConfigurer
?接口。import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;@Configuration @EnableWebMvc public class MyWebMvcConfig implements WebMvcConfigurer {// 自定義配置在這里添加 } ?
-
配置視圖解析器:
通過實現?configureViewResolvers
?方法,可以自定義視圖解析器。import org.springframework.web.servlet.config.annotation.ViewResolverRegistry;@Override public void configureViewResolvers(ViewResolverRegistry registry) {registry.jsp("/WEB-INF/views/", ".jsp"); } ?
-
添加攔截器:
通過實現?addInterceptors
?方法,可以添加攔截器。import org.springframework.web.servlet.config.annotation.InterceptorRegistry;@Override public void addInterceptors(InterceptorRegistry registry) {registry.addInterceptor(new MyInterceptor()).addPathPatterns("/**"); } ?
-
配置跨域請求:
通過實現?addCorsMappings
?方法,可以配置跨域請求。import org.springframework.web.servlet.config.annotation.CorsRegistry;@Override public void addCorsMappings(CorsRegistry registry) {registry.addMapping("/**").allowedOrigins("http://example.com").allowedMethods("GET", "POST", "PUT", "DELETE").allowCredentials(true).maxAge(3600); } ?
-
添加靜態資源處理:
通過實現?addResourceHandlers
?方法,可以配置靜態資源的處理。import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;@Override public void addResourceHandlers(ResourceHandlerRegistry registry) {registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/"); } ?
-
配置消息轉換器:
通過實現?configureMessageConverters
?方法,可以添加或自定義消息轉換器。import org.springframework.http.converter.HttpMessageConverter;@Override public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {converters.add(new MyCustomMessageConverter()); } ?