尧图网络 高端网站定制 · 原创设计
免费咨询热线
400-888-6620
免费获取方案
Spring Boot 3 REST API 工程化实践:校验、异常、日志与测试
写出一个能返回 JSON 的接口并不难难的是让几十个接口长期保持一致参数错误要容易定位业务异常不能泄露堆栈日志能够串起一次请求重构后还要有测试兜底。本文以Java 17、Spring Boot 3.x为基础搭建一套小而完整的 REST API 骨架。示例使用 Spring Boot 3 对应的jakarta.*包。1. 先确定接口契约业务响应可以统一外形但不能抹掉 HTTP 状态码的语义。例如参数错误仍应返回400资源不存在返回404未知服务端错误返回500。import java.time.Instant; ​ public record ApiResponseT( String code, String message, T data, String traceId, Instant timestamp ) { public static T ApiResponseT success(T data, String traceId) { return new ApiResponse(OK, success, data, traceId, Instant.now()); } ​ public static T ApiResponseT failure( String code, String message, T data, String traceId) { return new ApiResponse(code, message, data, traceId, Instant.now()); } }code是稳定的机器可读标识message面向人类traceId用于查日志。不要让前端根据可能变化的中文提示判断业务分支。项目至少需要 Web、Validation 和 Test 三组依赖dependency groupIdorg.springframework.boot/groupId artifactIdspring-boot-starter-web/artifactId /dependency dependency groupIdorg.springframework.boot/groupId artifactIdspring-boot-starter-validation/artifactId /dependency dependency groupIdorg.springframework.boot/groupId artifactIdspring-boot-starter-test/artifactId scopetest/scope /dependency2. 在入口完成参数校验请求对象只描述输入返回对象只描述输出避免把数据库实体直接暴露给 API。import jakarta.validation.constraints.Email; import jakarta.validation.constraints.Max; import jakarta.validation.constraints.Min; import jakarta.validation.constraints.NotBlank; import jakarta.validation.constraints.NotNull; import jakarta.validation.constraints.Size; ​ public record CreateUserRequest( NotBlank(message name must not be blank) Size(max 50, message name length must be 50) String name, ​ NotBlank(message email must not be blank) Email(message email format is invalid) String email, ​ NotNull(message age must not be null) Min(value 18, message age must be 18) Max(value 120, message age must be 120) Integer age ) {} ​ public record UserView(Long id, String name, String email, Integer age) {}控制器只负责协议转换。Valid触发请求体校验业务规则则留在 Service 中。import jakarta.validation.Valid; import org.slf4j.MDC; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; ​ RestController RequestMapping(/api/users) public class UserController { private final UserService userService; ​ public UserController(UserService userService) { this.userService userService; } ​ PostMapping ResponseStatus(HttpStatus.CREATED) public ApiResponseUserView create(Valid RequestBody CreateUserRequest request) { UserView user userService.create(request); return ApiResponse.success(user, MDC.get(traceId)); } }Bean Validation 只判断字段是否合法。诸如“邮箱是否已注册”“库存是否充足”需要访问业务数据应由 Service 判断并抛出业务异常。3. 为业务错误建立稳定分类public enum ErrorCode { INVALID_ARGUMENT, USER_NOT_FOUND, EMAIL_ALREADY_EXISTS, INTERNAL_ERROR } ​ public class BusinessException extends RuntimeException { private final ErrorCode code; ​ public BusinessException(ErrorCode code, String message) { super(message); this.code code; } ​ public ErrorCode getCode() { return code; } }错误码是对外契约。已经发布的含义不要随意复用内部数据库异常也不要原样返回给调用方。4. 用全局异常处理保持一致RestControllerAdvice把异常集中映射为状态码和响应体控制器不需要重复try/catch。import jakarta.validation.ConstraintViolationException; import java.util.LinkedHashMap; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.slf4j.MDC; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.http.converter.HttpMessageNotReadableException; import org.springframework.web.bind.MethodArgumentNotValidException; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RestControllerAdvice; ​ RestControllerAdvice public class GlobalExceptionHandler { private static final Logger log LoggerFactory.getLogger(GlobalExceptionHandler.class); ​ ExceptionHandler(MethodArgumentNotValidException.class) public ResponseEntityApiResponseMapString, String handleValidation( MethodArgumentNotValidException exception) { MapString, String fields new LinkedHashMap(); exception.getBindingResult().getFieldErrors().forEach(error - fields.putIfAbsent(error.getField(), error.getDefaultMessage())); ​ return ResponseEntity.badRequest().body(ApiResponse.failure( ErrorCode.INVALID_ARGUMENT.name(), request validation failed, fields, traceId())); } ​ ExceptionHandler(ConstraintViolationException.class) public ResponseEntityApiResponseVoid handleConstraint( ConstraintViolationException exception) { return ResponseEntity.badRequest().body(ApiResponse.failure( ErrorCode.INVALID_ARGUMENT.name(), exception.getMessage(), null, traceId())); } ​ ExceptionHandler(HttpMessageNotReadableException.class) public ResponseEntityApiResponseVoid handleUnreadableBody() { return ResponseEntity.badRequest().body(ApiResponse.failure( ErrorCode.INVALID_ARGUMENT.name(), request body is malformed, null, traceId())); } ​ ExceptionHandler(BusinessException.class) public ResponseEntityApiResponseVoid handleBusiness(BusinessException exception) { HttpStatus status exception.getCode() ErrorCode.USER_NOT_FOUND ? HttpStatus.NOT_FOUND : HttpStatus.CONFLICT; return ResponseEntity.status(status).body(ApiResponse.failure( exception.getCode().name(), exception.getMessage(), null, traceId())); } ​ ExceptionHandler(Exception.class) public ResponseEntityApiResponseVoid handleUnexpected(Exception exception) { log.error(Unhandled request exception, exception); return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body( ApiResponse.failure(ErrorCode.INTERNAL_ERROR.name(), internal server error, null, traceId())); } ​ private String traceId() { return MDC.get(traceId); } }最后的兜底处理器必须记录完整异常但响应只返回受控信息。把 SQL、类名或堆栈发给客户端既不稳定也可能泄露系统细节。5. 给每次请求添加 traceIdMDC 会把 traceId 带入同一线程产生的日志。由于线程池会复用线程清理 MDC 是必需步骤。import jakarta.servlet.FilterChain; import jakarta.servlet.ServletException; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.UUID; import org.slf4j.MDC; import org.springframework.core.Ordered; import org.springframework.core.annotation.Order; import org.springframework.stereotype.Component; import org.springframework.web.filter.OncePerRequestFilter; ​ Component Order(Ordered.HIGHEST_PRECEDENCE) public class TraceIdFilter extends OncePerRequestFilter { private static final String TRACE_ID traceId; ​ Override protected void doFilterInternal( HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { String traceId UUID.randomUUID().toString().replace(-, ); MDC.put(TRACE_ID, traceId); response.setHeader(X-Trace-Id, traceId); try { filterChain.doFilter(request, response); } finally { MDC.remove(TRACE_ID); } } }在 Logback pattern 中加入%X{traceId:-no-trace}即可打印该值。分布式系统中应优先接入 OpenTelemetry 等追踪方案并遵循统一的 trace context而不是让每个服务各自生成互不关联的 ID。6. 用接口测试锁定行为下面的测试验证三个关键契约HTTP 状态、稳定错误码和字段级错误信息。import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.when; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; ​ import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.context.annotation.Import; import org.springframework.http.MediaType; import org.springframework.test.web.servlet.MockMvc; ​ WebMvcTest(UserController.class) Import({GlobalExceptionHandler.class, TraceIdFilter.class}) class UserControllerTest { Autowired private MockMvc mockMvc; ​ MockBean private UserService userService; ​ Test void shouldRejectInvalidEmail() throws Exception { mockMvc.perform(post(/api/users) .contentType(MediaType.APPLICATION_JSON) .content( {name:Alice,email:bad-email,age:20} )) .andExpect(status().isBadRequest()) .andExpect(jsonPath($.code).value(INVALID_ARGUMENT)) .andExpect(jsonPath($.data.email).value(email format is invalid)) .andExpect(jsonPath($.traceId).isNotEmpty()); } ​ Test void shouldCreateUser() throws Exception { when(userService.create(any())).thenReturn( new UserView(1L, Alice, aliceexample.com, 20)); ​ mockMvc.perform(post(/api/users) .contentType(MediaType.APPLICATION_JSON) .content( {name:Alice,email:aliceexample.com,age:20} )) .andExpect(status().isCreated()) .andExpect(jsonPath($.code).value(OK)) .andExpect(jsonPath($.data.id).value(1)); } }Service 还应单独测试业务分支涉及数据库约束时再增加包含真实数据库行为的集成测试。只依赖 MockMvc 无法发现 SQL、事务和数据库方言问题。7. 上线前检查清单HTTP 状态码与业务错误码各司其职错误码含义稳定。DTO 使用jakarta.validationController 参数确实添加了Valid。未知异常记录堆栈但响应不暴露内部实现。日志包含 traceId过滤器和异步任务都会清理 MDC。API 测试覆盖成功、校验失败、业务冲突和未知异常。时间、分页、空值和金额等字段有明确的序列化约定。总结REST API 的工程质量来自一致的边界DTO 负责输入约束Service 负责业务规则异常处理器负责协议映射traceId 负责定位请求测试负责锁定契约。这套骨架并不复杂却能显著减少重复代码也让后续增加鉴权、审计和链路追踪时有清晰的落点。
RELATED

相关推荐

SpringBoot+Vue图书商城系统开发实践

SpringBoot+Vue图书商城系统开发实践

1. 项目概述这个图书商城管理系统是我去年为一个高校图书馆开发的线上借阅平台,采用前后端分离架构,后端基于SpringBootMyBatisMySQL技术栈,前端使用Vue.js框架。系统上线后日均访问量稳定在3000,成功替代了原有的手工登记模式。提…

📅 2026/10/11 18:59:31
彻底解决C盘空间不足:深入解析Windows休眠文件Hiberfil.sys的删除与优化

彻底解决C盘空间不足:深入解析Windows休眠文件Hiberfil.sys的删除与优化

1. 项目概述:当C盘亮起红灯,我们该做什么?“C盘空间不足”大概是每个Windows用户都绕不开的经典难题。那个小小的红色进度条,就像悬在头顶的达摩克利斯之剑,随时可能让系统变卡、软件崩溃,甚至更新失败。面…

📅 2026/9/8 17:57:23
C++实现带约束最大子段和:从算法竞赛题目解析到工程实践

C++实现带约束最大子段和:从算法竞赛题目解析到工程实践

1. 项目概述与核心需求解析看到“打卡信奥刷题(2146)用C实现信奥 P12190 [蓝桥杯 2025 省 Java C] 小说”这个标题,我第一反应是,这题目信息量不小,而且有点“跨界”的味道。它本质上是一个典型的算法竞赛题目&#xf…

📅 2026/10/5 4:51:15
MORE NEWS

更多资讯

📰

数据结构——顺序表细致讲解

耕耘 :C、C、嵌入式技术领域 🔥我的个人主页 ❄️个人专栏:《C语言专栏》 《嵌入式专栏》 《数据结构专栏》 ✨**不要等待机会,而要创造机会!**✨ 📽博主简介: ✨✨一位热爱生活的阳光大男孩.✨✨ 前言 本文系统讲…

📰

小白程序员必看:字节新岗位AI Agent开发火爆,如何精准入行?

字节2027校招新增AI Agent开发岗,行业人才需求同比增长244%,但企业仍不清楚理想候选人标准。文章指出,当前招聘多依赖工具清单(如LangChain、RAG等),但技术迭代快导致筛选失效。建议企业通过测可迁移能力&a…

📰

AI中控与直播伴侣的联动配置和排查思路

四季度开播旺季,不少技术向的读者在搭自播工作台时遇到同一个现象:直播伴侣正常推流,AI 中控也在运行,但两边就是各干各的——话术识别不弹商品,弹幕不自动回复。本文按链路排查的思路,把联动配置和常见断点…

📰

用AI搭建一人调研团队:主编+三个AI工种+两本手册的实操框架

先说个直觉:这个标题看着像段子,但它背后其实是一套特别现实的调研工作流。我从去年开始在某内容团队里反复试“一个人扛下所有调研”的做法,试到后面实在受不了——又要定选题,又要查资料,又要分析趋势,又…

📰

低代码平台岗位管理实战:用户角色权限体系的设计与落地

上一期把报名排课和学员档案理顺之后,整个MBA培训管理系统终于能跑起来了。但我很快发现一个躲不开的问题:教务、班主任、讲师、助教、学员,不同角色都涌进来,总不能给所有人开同一套菜单、同一套按钮。你说一个普通学员能看到“讲…

📰

五大湖生态-经济耦合建模:Python实现水位、污染与渔业协同仿真

简介:本资源是面向2024年美国大学生数学建模竞赛(MCM/ICM)ICM D题——五大湖水资源系统建模与政策分析的深度解析资料包,专为参赛学生、指导教师及环境系统建模初学者设计,聚焦复杂水文-社会耦合系统的建模思路、数据处…

TODAY

今日更新

THIS WEEK

本周精选

THIS MONTH

本月热门

读完文章,想聊聊您的网站?

告诉我们您的行业与需求,资深顾问一对一梳理方案与报价,全程免费。

📞 💬