【Java定义统一返回类型】

@Data
@ApiModel(value = "接口返回对象", description = "接口返回对象")
public class Result<T> implements Serializable {

    private static final long serialVersionUID = 1L;

    /**
     * 返回处理消息
     */
    @ApiModelProperty(value = "返回处理消息")
    private String message = "操作成功!";

    /**
     * 返回代码
     */
    @ApiModelProperty(value = "返回代码")
    private Integer code = 0;

    /**
     * 返回数据对象 data
     */
    @ApiModelProperty(value = "返回数据对象")
    private T data;

    /**
     * 时间戳
     */
    @ApiModelProperty(value = "时间戳")
    private long timestamp = System.currentTimeMillis();

    public boolean ok()
    {
        return CommonConstant.SC_OK_200.equals(this.code);
    }

    public Result() {

    }

    /**
     * success自定义返回信息
     */
    public static <T> Result<T> success(String msg, T data) {
        Result<T> r = new Result<T>();
        r.setCode(CommonConstant.SC_OK_200);
        r.setMessage(msg);
        r.setData(data);
        return r;
    }

    /**
     * fail自定义返回信息
     */
    public static <T> Result<T> fail(String msg, T data) {
        Result<T> r = new Result<T>();
        r.setCode(CommonConstant.SC_INTERNAL_SERVER_ERROR_500);
        r.setMessage(msg);
        r.setData(data);
        return r;
    }

    public static <T> Result<T> success(T data) {
        Result<T> r = new Result<T>();
        r.setCode(CommonConstant.SC_OK_200);
        r.setMessage(CommonConstant.SUCCESS);
        r.setData(data);
        return r;
    }

    public static <T> Result<T> fail(T data) {
        Result<T> r = new Result<T>();
        r.setCode(CommonConstant.SC_INTERNAL_SERVER_ERROR_500);
        r.setMessage(CommonConstant.FAIL);
        r.setData(data);
        return r;
    }

    public static <T> Result<T> success(String msg) {
        Result<T> r = new Result<T>();
        r.setCode(CommonConstant.SC_OK_200);
        r.setMessage(msg);
        return r;
    }

    public static <T> Result<T> fail(String msg) {
        Result<T> r = new Result<T>();
        r.setCode(CommonConstant.SC_INTERNAL_SERVER_ERROR_500);
        r.setMessage(msg);
        return r;
    }
}
public interface CommonConstant {

	/** {@code 500 Server Error} (HTTP/1.0 - RFC 1945) */
    public static final Integer SC_INTERNAL_SERVER_ERROR_500 = 500;
    /** {@code 200 OK} (HTTP/1.0 - RFC 1945) */
    public static final Integer SC_OK_200 = 200;

    /**
     *调用接口状态:成功
     */
    public static final String SUCCESS = "成功";

    /**
     *调用接口状态:失败
     */
    public static final String FAIL = "失败";

}

你可能感兴趣的:(个人笔记,Java,spring,springboot,intellij-idea,java)