大多数公司使用的都是前后端分离框架,例如springboot+vue,springboot+react等,因此,前后端的数据交互是非常重要的。
本文实现springboot对统一返回结果进行封装,方便前后端交互。
使用lombok中的@Data注解可以省略实体类的get、set方法。
pom.xml中引入lombok依赖
<!-- lombok简化开发 -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.8</version>
<scope>provided</scope>
</dependency>
这里的ResultUtil.class文件中,提供无参私有构造方法的意义在于,程序员只能使用ResultUtil的静态方法,而不允许对其进行new操作。
ResultUtil中使用重载,提供4种success方法和5种fail方法,可以根据场景自行进行添加删除。
ResultUtil类
import lombok.Data;
/**
* @author yeqc
* @date 2022/3/28 21:54
*/
@Data
public class ResultUtil<T> {
public static final Integer SUCCESS_CODE = 2000;
public static final Integer FAIL_CODE = 4000;
public static final String SUCCESS_MESSAGE = "success";
public static final String FAIL_MESSAGE = "fail";
/**
* 返回状态码
*/
private Integer code;
/**
* 返回信息
*/
private String message;
/**
* 返回数据
*/
private T data;
private ResultUtil() {
}
public static <T> ResultUtil<T> success() {
ResultUtil<T> resultUtil = new ResultUtil<>();
resultUtil.setCode(SUCCESS_CODE);
resultUtil.setMessage(SUCCESS_MESSAGE);
return resultUtil;
}
public static <T> ResultUtil<T> success(T data) {
ResultUtil<T> resultUtil = success();
resultUtil.setData(data);
return resultUtil;
}
public static <T> ResultUtil<T> success(String message, T data) {
ResultUtil<T> resultUtil = success();
resultUtil.setMessage(message);
resultUtil.setData(data);
return resultUtil;
}
public static <T> ResultUtil<T> success(Integer code, String message, T data) {
ResultUtil<T> resultUtil = new ResultUtil<>();
resultUtil.setCode(code);
resultUtil.setMessage(message);
resultUtil.setData(data);
return resultUtil;
}
public static <T> ResultUtil<T> fail() {
ResultUtil<T> resultUtil = new ResultUtil<>();
resultUtil.setCode(FAIL_CODE);
resultUtil.setMessage(FAIL_MESSAGE);
return resultUtil;
}
public static <T> ResultUtil<T> fail(T data) {
ResultUtil<T> resultUtil = fail();
resultUtil.setData(data);
return resultUtil;
}
public static <T> ResultUtil<T> fail(String message, T data) {
ResultUtil<T> resultUtil = fail();
resultUtil.setMessage(message);
resultUtil.setData(data);
return resultUtil;
}
public static <T> ResultUtil<T> fail(Integer code, String message) {
ResultUtil<T> resultUtil = fail();
resultUtil.setCode(code);
resultUtil.setMessage(message);
return resultUtil;
}
public static <T> ResultUtil<T> fail(Integer code, String message, T data) {
ResultUtil<T> resultUtil = new ResultUtil<>();
resultUtil.setCode(code);
resultUtil.setMessage(message);
resultUtil.setData(data);
return resultUtil;
}
}
测试案例
@RestController
public class TestController {
@GetMapping("/test")
public ResultUtil<Boolean> test() {
return ResultUtil.success(true);
}
}