写出一个能返回 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 负责定位请求测试负责锁定契约。这套骨架并不复杂却能显著减少重复代码也让后续增加鉴权、审计和链路追踪时有清晰的落点。