Spring Boot 3:实现统一结果封装
本帖最后由 Shaw0xyz 于 2024-5-19 13:48 编辑在现代Web应用开发中,统一的API响应格式能够显著提高前后端协作效率,便于调试和维护。本文将介绍如何在Spring Boot 3中实现统一的结果封装。
为什么需要统一结果封装?
统一的API响应格式带来了以下好处:
1. 一致性:前端无需处理多种响应格式。
2. 可读性:明确的响应结构便于理解和调试。
3. 可维护性:错误处理和日志记录更简洁。
定义统一的响应结构
首先,我们定义一个标准的响应结构。通常包含以下字段:
- code:状态码,标识请求是否成功。
- message:响应信息,描述请求处理结果。
- data:响应数据,承载实际业务数据。
在`src/main/java/com/example/demo`目录下创建一个新的包`response`,并在其中创建`ApiResponse`类:
package com.example.demo.response;
public class ApiResponse<T> {
private int code;
private String message;
private T data;
public ApiResponse() {}
public ApiResponse(int code, String message, T data) {
this.code = code;
this.message = message;
this.data = data;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
public static <T> ApiResponse<T> success(T data) {
return new ApiResponse<>(200, "Success", data);
}
public static <T> ApiResponse<T> error(int code, String message) {
return new ApiResponse<>(code, message, null);
}
}
统一响应处理
为了确保所有的API响应都遵循上述结构,我们可以使用Spring的`@ControllerAdvice`和`@ExceptionHandler`注解。
在`response`包中创建一个名为`GlobalExceptionHandler`的类:
package com.example.demo.response;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(Exception.class)
public ResponseEntity<ApiResponse<?>> handleException(Exception e) {
return new ResponseEntity<>(ApiResponse.error(500, "Internal Server Error: " + e.getMessage()), HttpStatus.INTERNAL_SERVER_ERROR);
}
// 处理自定义异常
@ExceptionHandler(CustomException.class)
public ResponseEntity<ApiResponse<?>> handleCustomException(CustomException e) {
return new ResponseEntity<>(ApiResponse.error(e.getCode(), e.getMessage()), HttpStatus.BAD_REQUEST);
}
}
自定义异常
我们可以定义自己的异常类,以便在业务逻辑中抛出并由全局异常处理器捕获:
package com.example.demo.response;
public class CustomException extends RuntimeException {
private int code;
public CustomException(int code, String message) {
super(message);
this.code = code;
}
public int getCode() {
return code;
}
}
控制器中的统一响应
在控制器中使用`ApiResponse`来封装响应结果。例如:
package com.example.demo.controller;
import com.example.demo.response.ApiResponse;
import com.example.demo.response.CustomException;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class DemoController {
@GetMapping("/hello")
public ApiResponse<String> hello(@RequestParam(value = "name", defaultValue = "World") String name) {
if ("error".equals(name)) {
throw new CustomException(400, "Invalid name");
}
return ApiResponse.success("Hello, " + name);
}
}
测试统一响应
启动Spring Boot应用,访问`http://localhost:8080/hello`,应该会得到如下JSON响应:
{
"code": 200,
"message": "Success",
"data": "Hello, World"
}
访问`http://localhost:8080/hello?name=error`,应该会得到如下JSON响应:
{
"code": 400,
"message": "Invalid name",
"data": null
}
结语
通过本文的介绍,我们学习了如何在Spring Boot 3中实现统一的结果封装。统一响应格式不仅提高了代码的可读性和维护性,还简化了前后端的协作。
页:
[1]