当前位置: 代码网 > it编程>编程语言>Java > 在SpringBoot里自定义Spring MVC配置的三种方法

在SpringBoot里自定义Spring MVC配置的三种方法

2026年03月21日 Java 我要评论
前言springboot 帮我们自动配好了 mvc 的核心组件,但实际开发中,光用默认配置肯定不够:比如想改静态资源路径、加自定义拦截器、换消息转换器、调整请求参数解析规则…&helli

前言

springboot 帮我们自动配好了 mvc 的核心组件,但实际开发中,光用默认配置肯定不够:

比如想改静态资源路径、加自定义拦截器、换消息转换器、调整请求参数解析规则……这些都需要我们自定义 spring mvc 配置。

今天就教你 3 种自定义 spring mvc 配置的方法,从简单到复杂,新手也能一步步跟着做,再也不用对着默认配置束手无策。

先搞懂springboot 里自定义 mvc 配置的“规矩”

springboot 为了不让我们乱改配置,定了一个核心规则:
想要自定义 mvc 配置,必须实现 webmvcconfigurer 接口(或继承 webmvcconfigureradapter,但 3.x 已废弃),并加上 @configuration 注解

这个接口里全是默认方法(不用全部实现,按需重写),覆盖了 mvc 配置的所有场景:静态资源、拦截器、消息转换器、视图解析器……

先给个基础模板,所有自定义配置都基于这个结构:

importorg.springframework.context.annotation.configuration;
importorg.springframework.web.servlet.config.annotation.webmvcconfigurer;
// 标记这是配置类,springboot 启动时会扫描并加载
@configuration
publicclasscustomwebmvcconfigimplementswebmvcconfigurer{
// 下面重写需要自定义的方法即可
// 自定义静态资源路径、添加拦截器、配置消息转换器……
}

踩坑提醒:千万别加 @enablewebmvc 注解!
加了这个注解,springboot 会完全关闭默认的 mvc 自动配置,所有配置都要你自己写(包括 dispatcherservlet、参数解析器这些核心组件),新手大概率会配崩。

最简单的自定义——修改静态资源访问路径

springboot 默认的静态资源路径是 classpath:/static/classpath:/public/classpath:/resources/,比如你在 static 下放个 test.jpg,访问地址是 http://localhost:8080/test.jpg

如果想加自定义路径(比如 classpath:/images/),或者改默认优先级,重写 addresourcehandlers 方法就行:

importorg.springframework.context.annotation.configuration;
importorg.springframework.web.servlet.config.annotation.resourcehandlerregistry;
importorg.springframework.web.servlet.config.annotation.webmvcconfigurer;
@configuration
publicclasscustomwebmvcconfigimplementswebmvcconfigurer{
// 自定义静态资源配置
@override
publicvoidaddresourcehandlers(resourcehandlerregistry registry){
// 1. 添加自定义静态资源路径:classpath:/images/
// addresourcehandler:前端访问路径前缀
// addresourcelocations:本地资源实际路径
        registry.addresourcehandler("/images/**")// 前端访问 http://localhost:8080/images/xxx.jpg
addresourcelocations("classpath:/images/");// 对应项目里的 src/main/resources/images/
// 2. 覆盖默认静态资源路径(可选,不推荐,保留默认更灵活)
// registry.addresourcehandler("/**")
//         .addresourcelocations("classpath:/my-static/");
}
}

测试:在 src/main/resources/images/ 下放 logo.png,访问 http://localhost:8080/images/logo.png 就能看到图片。

最常用的自定义——添加全局拦截器

开发中经常需要用拦截器做登录校验、接口限流、日志记录,这是自定义 mvc 最核心的场景。

步骤分两步:先写拦截器类,再在 mvc 配置里注册。

第一步:写自定义拦截器

importjakarta.servlet.http.httpservletrequest;
importjakarta.servlet.http.httpservletresponse;
importorg.springframework.web.servlet.handlerinterceptor;
importorg.springframework.web.servlet.modelandview;
// 自定义登录拦截器
publicclasslogininterceptorimplementshandlerinterceptor{
// 请求处理前执行(核心逻辑写这里)
@override
publicbooleanprehandle(httpservletrequest request,httpservletresponse response,object handler)throwsexception{
// 模拟:从请求头获取 token,判断是否登录
string token = request.getheader("token");
if(token ==null||!"admin123".equals(token)){
// 未登录,返回 401 状态码
            response.setstatus(401);
            response.getwriter().write("未登录,请先登录!");
returnfalse;// 拦截请求,不往下走
}
returntrue;// 放行请求
}
// 请求处理后执行(可选)
@override
publicvoidposthandle(httpservletrequest request,httpservletresponse response,object handler,modelandview modelandview)throwsexception{
handlerinterceptor.super.posthandle(request, response, handler, modelandview);
}
// 整个请求完成后执行(可选,比如清理资源)
@override
publicvoidaftercompletion(httpservletrequest request,httpservletresponse response,object handler,exception ex)throwsexception{
handlerinterceptor.super.aftercompletion(request, response, handler, ex);
}
}

第二步:在 mvc 配置里注册拦截器

importorg.springframework.context.annotation.bean;
importorg.springframework.context.annotation.configuration;
importorg.springframework.web.servlet.config.annotation.interceptorregistry;
importorg.springframework.web.servlet.config.annotation.webmvcconfigurer;
@configuration
publicclasscustomwebmvcconfigimplementswebmvcconfigurer{
// 把拦截器注册为 bean,spring 才能管理
@bean
publiclogininterceptorlogininterceptor(){
returnnewlogininterceptor();
}
// 注册拦截器,并配置拦截规则
@override
publicvoidaddinterceptors(interceptorregistry registry){
        registry.addinterceptor(logininterceptor())
.addpathpatterns("/**")// 拦截所有请求
.excludepathpatterns("/login","/hello");// 排除登录、hello 接口(不拦截)
}
}

测试:

  • 访问 http://localhost:8080/hello:不用 token,正常返回(排除拦截);
  • 访问 http://localhost:8080/user/info:不加 token 会返回 401,加 token: admin123 请求头才放行。

进阶自定义——替换/新增消息转换器

spring mvc 默认用 mappingjackson2httpmessageconverter 处理 json 序列化/反序列化,但有时我们想自定义规则(比如日期格式、空值处理),或者换用 fastjson 作为转换器。

以“自定义 jackson 日期格式”为例:

importcom.fasterxml.jackson.databind.objectmapper;
importcom.fasterxml.jackson.databind.serializationfeature;
importcom.fasterxml.jackson.datatype.jsr310.javatimemodule;
importcom.fasterxml.jackson.datatype.jsr310.ser.localdatetimeserializer;
importorg.springframework.context.annotation.bean;
importorg.springframework.context.annotation.configuration;
importorg.springframework.http.converter.httpmessageconverter;
importorg.springframework.http.converter.json.mappingjackson2httpmessageconverter;
importorg.springframework.web.servlet.config.annotation.webmvcconfigurer;
importjava.time.localdatetime;
importjava.time.format.datetimeformatter;
importjava.util.list;
@configuration
publicclasscustomwebmvcconfigimplementswebmvcconfigurer{
// 自定义 json 消息转换器
@override
publicvoidconfiguremessageconverters(list<httpmessageconverter<?>> converters){
// 1. 创建 jackson 对象映射器,自定义序列化规则
objectmapper objectmapper =newobjectmapper();
// 处理 localdatetime 日期格式
javatimemodule javatimemodule =newjavatimemodule();
        javatimemodule.addserializer(localdatetime.class,
newlocaldatetimeserializer(datetimeformatter.ofpattern("yyyy-mm-dd hh:mm:ss")));
        objectmapper.registermodule(javatimemodule);
// 关闭默认的日期序列化(避免转成时间戳)
        objectmapper.disable(serializationfeature.write_dates_as_timestamps);
// 2. 创建自定义的消息转换器
mappingjackson2httpmessageconverter converter =newmappingjackson2httpmessageconverter();
        converter.setobjectmapper(objectmapper);
// 3. 把自定义转换器加到列表最前面(优先级最高)
        converters.add(0, converter);
}
}

测试:返回包含 localdatetime 类型的对象时,日期会按 yyyy-mm-dd hh:mm:ss 格式显示,而不是默认的时间戳或 iso 格式。

新手常见问题(避坑清单)

自定义配置不生效?

  • 检查 @configuration 注解有没有加;
  • 检查配置类是否在主启动类的扫描包下;
  • 别加 @enablewebmvc(除非你想完全自定义)。

拦截器里注入 service 为 null?

  • 原因:拦截器不是 spring 管理的 bean,直接 new 会导致依赖注入失败;
  • 解决:像上面那样,用 @bean 注解把拦截器注册为 spring bean,再通过方法引用获取。

静态资源访问 404?

最后总结

springboot 里自定义 spring mvc 配置,核心就 3 点:

  • 检查 addresourcehandlers 里的路径是否写对(classpath:/ 别漏,/** 通配符别少);
  • 别覆盖默认静态资源路径,优先用添加(add)而非替换。
  • 实现 webmvcconfigurer 接口 + 加 @configuration
  • 按需重写接口里的方法(静态资源、拦截器、消息转换器等);
  • 别加 @enablewebmvc,保留 springboot 自动配置的基础。

以上就是在springboot里自定义spring mvc配置的三种方法的详细内容,更多关于springboot自定义spring mvc配置的资料请关注代码网其它相关文章!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2026  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com