在 Spring Boot 中使用 WebMvcConfigurer

WebMvcConfigurer 是 Spring MVC 提供的一个扩展接口,用于配置 Spring MVC 的各种功能。在 Spring Boot 应用中,通过实现 WebMvcConfigurer 接口,可以定制和扩展默认的 Spring MVC 配置。以下是对 WebMvcConfigurer 的详细解析及其常见用法。

一、基本概念

WebMvcConfigurer 接口提供了一组回调方法,用于配置 Spring MVC 的各种方面,如视图解析器、拦截器、跨域请求、消息转换器等。通过实现这些方法,可以方便地自定义 MVC 配置。

二、实现 WebMvcConfigurer
  1. 创建配置类
    在 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 {// 自定义配置在这里添加
    }
    ​
    
  2. 配置视图解析器
    通过实现 configureViewResolvers 方法,可以自定义视图解析器。

    import org.springframework.web.servlet.config.annotation.ViewResolverRegistry;@Override
    public void configureViewResolvers(ViewResolverRegistry registry) {registry.jsp("/WEB-INF/views/", ".jsp");
    }
    ​
    
  3. 添加拦截器
    通过实现 addInterceptors 方法,可以添加拦截器。

    import org.springframework.web.servlet.config.annotation.InterceptorRegistry;@Override
    public void addInterceptors(InterceptorRegistry registry) {registry.addInterceptor(new MyInterceptor()).addPathPatterns("/**");
    }
    ​
    
  4. 配置跨域请求
    通过实现 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);
    }
    ​
    
  5. 添加静态资源处理
    通过实现 addResourceHandlers 方法,可以配置静态资源的处理。

    import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;@Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
    }
    ​
    
  6. 配置消息转换器
    通过实现 configureMessageConverters 方法,可以添加或自定义消息转换器。

    import org.springframework.http.converter.HttpMessageConverter;@Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {converters.add(new MyCustomMessageConverter());
    }
    ​