MENU

springboot定义统一返回类

March 15, 2021 • 开发

①在主包目录下,首先新建一个common目录,用于存放这些公共方法等

②在common目录下,新建一个枚举类,命名为ResCode.java

package com.demonation.demo.common;

/**
 * @author xupt
 */

public enum ResCode {
    /**
     * success成功返回
     * error失败返回
     */
    SUCCESS(1, "success"),
    ERROR(0, "error");
    private Integer code;
    private String msg;
    ResCode(Integer code, String msg) {
        this.code=code;
        this.msg=msg;
    }

    public Integer getCode() {
        return code;
    }

    public String getMsg() {
        return msg;
    }
}

③在common目录下,新建一个类,命名为ResultVO.java

package com.demonation.demo.common;

import lombok.Data;

/**
 * @author xupt
 */
@Data
public class ResultVO {
    private Integer code;
    private String msg;
    private Object data;

    public ResultVO(ResCode resCode) {
        this.code = resCode.getCode();
        this.msg = resCode.getMsg();
    }

    public ResultVO(ResCode resCode, Object data) {
        this(resCode);
        this.data = data;
    }
}

④使用示例

@GetMapping("test")
public ResultVO test(){
       return new ResultVO(ResCode.SUCCESS,"输出正确");
}

输出为:

{
  "code": 1,
  "msg": "success",
  "data": "输出正确"
}
转载请注明出处,并添加原文地址

Archives QR Code Tip
QR Code for this page
Tipping QR Code