# pom.xml
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
# 枚举状态码定义
ResultCode.enum
import lombok.Getter;
/*
* @author chenbz
* @date 2020/09/23
* @description: 全局统一返回响应枚举类
* */
@Getter
public enum ResultCode {
//1000系列通用错误
SUCCESS(200, "操作成功"),
WARNING(201, "操作失败"),
FAILED(1001, "接口错误"),
VALIDATE_FAILED(1002, "参数校验失败"),
ERROR(500, "服务器内部错误"),
//2000系列用户错误
USER_NOT_EXIST(2000,"用户不存在"),
USER_LOGIN_FAIL(2001,"用户名或密码错误"),
USER_NOT_LOGIN(2002,"用户还未登录,请先登录"),
NO_PERMISSION(2003,"权限不足,请联系管理员");
private int code;
private String msg;
ResultCode(int code, String msg) {
this.code = code;
this.msg = msg;
}
}
# 实体类
Result.class
import lombok.Getter;
import lombok.Setter;
/*
* @author chenbz
* @date 2020/09/23
* @description: 全局统一返回实体类
* */
@Getter
@Setter
public class Result {
private int code;
private String msg;
private Object data;
}
# 统一响应体定义
ResultResponse.class
/*
* @author chenbz
* @date 2020/09/23
* @description: 自定义全局统一响应
* */
public class ResultResponse {
public static Result success() {
return resultResponse(ResultCode.SUCCESS, "");
}
public static Result success(Object data) {
return resultResponse(ResultCode.SUCCESS, data);
}
public static Result warning() {
return resultResponse(ResultCode.WARNING, "");
}
public static Result warning(Object data) {
return resultResponse(ResultCode.WARNING, data);
}
public static Result error() {
return resultResponse(ResultCode.ERROR, "");
}
public static Result error(Object data) {
return resultResponse(ResultCode.ERROR, data);
}
public static Result resultResponse(ResultCode resultCode, Object data) {
return resultResponse(resultCode.getCode(), resultCode.getMsg(), data);
}
public static Result resultResponse(int code, String msg, Object data) {
Result result = new Result();
result.setCode(code);
result.setMsg(msg);
result.setData(data);
return result;
}
}
# 测试
TestController.class
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/api/test")
public class TestController {
@GetMapping("/list")
public Result list() {
return ResultResponse.success();
}
}