SpringBoot統(tǒng)一數(shù)據(jù)返回格式的實現(xiàn)示例
在 Spring Boot 項目中,統(tǒng)一的數(shù)據(jù)格式返回是一種良好的實踐,它提高了代碼的可維護性和一致性,并改善了客戶端與服務端之間的通信。本文將介紹如何在 Spring Boot 中實現(xiàn)統(tǒng)一的數(shù)據(jù)格式返回。
1 為什么需要統(tǒng)一數(shù)據(jù)返回格式
- ?便前端程序員更好的接收和解析后端數(shù)據(jù)接?返回的數(shù)據(jù)。
- 降低前端程序員和后端程序員的溝通成本,按照某個格式實現(xiàn)就?了,因為所有接?都是這樣返回的。
- 有利于項?統(tǒng)?數(shù)據(jù)的維護和修改。
- 有利于后端技術部?的統(tǒng)?規(guī)范的標準制定,不會出現(xiàn)稀奇古怪的返回內(nèi)容。
2 統(tǒng)一數(shù)據(jù)返回格式的實現(xiàn)
統(tǒng)?的數(shù)據(jù)返回格式可以使? @ControllerAdvice + ResponseBodyAdvice 的?式實現(xiàn)。
- @ControllerAdvice是Spring框架提供的一個用于全局處理控制器的增強器注解。通過@ControllerAdvice注解的類,可以將對應的增強邏輯應用到所有的@Controller注解的控制器中。
- @ResponseBodyAdvice是一個用于處理響應體的接口。通過實現(xiàn)這個接口,可以在Controller方法返回之前和之后對響應體進行處理。
具體實現(xiàn)如下:
2.1 創(chuàng)建統(tǒng)一響應類
首先,我們需要創(chuàng)建一個統(tǒng)一的響應類,用于封裝 API 返回的數(shù)據(jù):
public class ApiResponse<T> {
private int status;
private String message;
private T data;
public ApiResponse(int status, String message, T data) {
this.status = status;
this.message = message;
this.data = data;
}
// Getters and Setters
}
2.2 創(chuàng)建統(tǒng)一響應處理類
這里使用@controller注解和ResponseBodyAdvice來實現(xiàn)
@ControllerAdvice
public class GlobalResponseBodyAdvice implements ResponseBodyAdvice<Object> {
@Override
public boolean supports(MethodParameter returnType, Class converterType) {
// 判斷是否需要處理響應體
return true;
}
@Override
public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,
Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
// 包裝響應體
if (body instanceof ApiResponse) {
return body;
}
return new ApiResponse<>(HttpStatus.OK.value(), "Success", body);
}
}

為了保證異常也能返回統(tǒng)一的數(shù)據(jù)格式,我們需要創(chuàng)建一個全局異常處理類,博客 講解了Spring Boot中如何進行統(tǒng)一異常處理。
@ControllerAdvice //添加完此注解后,此類隨著springboot項目的啟動而啟動,并且會監(jiān)控controller的異常.監(jiān)聽項目中所有的異常
@ResponseBody
public class MyExceptionAdvice {
//這里的一場都是意外異常,并不是業(yè)務異常,業(yè)務異常后端controller會處理返回給前端.業(yè)務異常會和前端溝通好已規(guī)定的狀態(tài)碼返回。
@ExceptionHandler(NullPointerException.class)
public ApiResponse<String> doNullPointerException(NullPointerException e){
ApiResponse<String> apiResponse = new ApiResponse<>(HttpStatus.INTERNAL_SERVER_ERROR.value(), e.getMessage(), null);
return apiResponse;
}
// 默認的異常處理,當有有異常出現(xiàn)的時候,會先匹配子類的異常,當所有的異常都沒有匹配的時候就會走這一條默認的一場路線業(yè)務。
@ExceptionHandler(Exception.class)
public ApiResponse<String> doException(Exception e){
ApiResponse<String> apiResponse = new ApiResponse<>(HttpStatus.INTERNAL_SERVER_ERROR.value(), e.getMessage(), null);
return apiResponse;
}
}2.3 controller模擬數(shù)據(jù)并返回
觀察異常出現(xiàn)情況下和正常訪問情況下,是否都實現(xiàn)了統(tǒng)一格式返回。
@RestController
@RequestMapping("/user")
public class UserController {
@RequestMapping("login")
public String login(){
Object obj = null;
System.out.println(obj.hashCode());
return "這里是login";
}
@GetMapping("/data")
public User getUserData() {
// 這個方法會返回一個User對象
User user = new User();
user.setId(1);
user.setName("張三");
user.setEmail("zhangsan@example.com");
return user;
}
@GetMapping("/success")
public Integer getSuccessMessage() {
// 這個方法會返回一個簡單的字符串
return 123456;
}
}
訪問:127.0.0.1:8080/user/login 可以看到異常信息被統(tǒng)一處理并統(tǒng)一格式后返回。

訪問127.0.0.1:8080/user/data ,可以看到接收到的數(shù)據(jù)也被統(tǒng)一處理。

訪問127.0.0.1:8080/user/success ,可以看到接收到的數(shù)據(jù)也被統(tǒng)一處理。

總結(jié)
通過上述步驟,我們實現(xiàn)了使用@ControllerAdvice和ResponseBodyAdvice統(tǒng)一API數(shù)據(jù)返回格式的功能。這種方式不僅簡化了代碼,還使得API響應格式一致,更加規(guī)范和易于維護。
到此這篇關于SpringBoot統(tǒng)一數(shù)據(jù)返回格式的實現(xiàn)示例的文章就介紹到這了,更多相關SpringBoot統(tǒng)一數(shù)據(jù)返回格式內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Spring Cloud基于zuul實現(xiàn)網(wǎng)關過程解析
這篇文章主要介紹了Spring Cloud基于zuul實現(xiàn)網(wǎng)關過程解析,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2019-12-12
解決SpringMVC 返回Java8 時間JSON數(shù)據(jù)的格式化問題處理
本篇文章主要介紹了解決SpringMVC 返回Java8 時間JSON數(shù)據(jù)的格式化問題處理,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-02-02

