博主
258
258
258
258
专辑

第五节 接口的公共返回类

亮子 2022-06-23 14:41:03 3255 0 0 0

1、添加依赖

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.14</version>
        </dependency>

2、工具类代码

package com.shenmazong.utils;

import lombok.Data;

/**
 * @author 军哥
 * @version 1.0
 * @description: 公共返回类
 * @date 2022/6/21 11:25
 */

@Data
public class ResultResponse {
    private boolean flag;
    private int code;
    private String msg;
    private Object data;

    /**
     * @description 私有化构造函数,防止被new
     * @author 军哥
     * @date 2022/6/21 11:35
     * @version 1.0
     */
    private ResultResponse() {

    }

    /**
     * @description 构造成功对象
     * @author 军哥
     * @date 2022/6/21 11:35
     * @version 1.0
     */
    public static ResultResponse SUCCESS(Object data) {
        ResultResponse result = new ResultResponse();
        result.setCode(200);
        result.setFlag(true);
        result.setMsg("操作成功");
        result.setData(data);

        return result;
    }

    /**
     * @description 默认成功构造对象
     * @author 军哥
     * @date 2022/6/21 11:36
     * @version 1.0
     */
    public static ResultResponse SUCCESS() {

        return ResultResponse.SUCCESS(null);
    }

    /**
     * @description 构造失败对象
     * @author 军哥
     * @date 2022/6/21 11:36
     * @version 1.0
     */
    public static ResultResponse FAILED(int code, String msg, Object data) {
        ResultResponse result = new ResultResponse();
        result.setCode(code);
        result.setFlag(false);
        result.setMsg(msg);
        result.setData(data);

        return result;
    }

    /**
     * @description 使用code构造失败对象
     * @author 军哥
     * @date 2022/6/21 11:36
     * @version 1.0
     */
    public static ResultResponse FAILED(int code) {
        return ResultResponse.FAILED(code, "操作失败", null);
    }

    /**
     * @description 使用code和msg构造失败对象
     * @author 军哥
     * @date 2022/6/21 11:36
     * @version 1.0
     */
    public static ResultResponse FAILED(int code, String msg) {
        return ResultResponse.FAILED(code, msg, null);
    }
}