Springboot中WebMvcConfigurer接口详解

用途:跨域、拦截器、静态资源处理

接口方法的作用:

    addInterceptors:拦截器
    addViewControllers:页面跳转
    addResourceHandlers:静态资源
    configureDefaultServletHandling:默认静态资源处理器
    configureViewResolvers:视图解析器
    configureContentNegotiation:配置内容裁决的一些参数
    addCorsMappings:跨域
    configureMessageConverters:信息转换器

   在Spring Boot 1.5版本都是靠重写WebMvcConfigurerAdapter的方法来添加自定义拦截器,消息转换器等。SpringBoot 2.0 后,该类被标记为@Deprecated(弃用)。官方推荐直接实现WebMvcConfigurer或者直接继承WebMvcConfigurationSupport,方式一实现     WebMvcConfigurer接口(推荐),方式二继承WebMvcConfigurationSupport类,具体实现可看这篇文章。https://blog.csdn.net/fmwind/article/details/82832758

复制代码
package com.olive.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * WebMvcConfigurer
 *
 */
@Configuration
@EnableWebMvc
public class ConfigurerAdapter implements WebMvcConfigurer {

    //图片保存路径
    public static final String PIC_PATH = "/landscape/";
    @Value(value="${application.profile}")
    private  String  profile;
  @Autowired
  private AuthorityInterceptor authorityInterceptor;
//跨域 @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") .allowCredentials(true) .allowedHeaders("*") .allowedOrigins("*") .allowedMethods("GET","POST","PUT","DELETE"); } // 可解决Long 类型在 前端精度丢失的问题, 如不想全局 直接添加注解 @JsonSerialize(using= ToStringSerializer.class) 到相应的字段 @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/**").addResourceLocations("classpath:/META-INF/resources/").setCachePeriod(0); /** 图片传路径 */ registry.addResourceHandler("/landscape/**").addResourceLocations("file:" + profile); }



  @Override
  public void addInterceptors(InterceptorRegistry registry{
    //注册自己的拦截器并设置拦截的请求路径
    registry.addInterceptor(authorityInterceptor).addPathPatterns("/**");
    super.addInterceptors(registry);
  }

}
复制代码

 

 

参考文章:https://blog.csdn.net/kuishao1314aa/article/details/109777304

posted on   周公  阅读(4432)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示