SpringBoot返回值封装

前提:SpringBoot整合MyBatis
为了后台返回值统一格式,在util包中创建Result类将返回值封装

public class Result <T> {

    private int code;       // 状态码
    private String msg;     // 返回的信息
    private T data;         // 返回的数据

    /**
     * 成功时候的调用(有数据)
     * @param data
     * @param <T>
     * @return
     */
    public static <T> Result<T> success(T data){
        return new Result<T>(data);
    }

    /**
     * 成功时候的调用(无数据)
     * @param <T>
     * @return
     */
    public static <T> Result<T> success(){
        return new Result<T>();
    }

    /**
     * 异常时候的调用(有msg参数)
     * @param msg
     * @param <T>
     * @return
     */
    public static <T> Result<T> error(String msg){
        return new Result<T>(msg);
    }

    /**
     * 异常时候的调用(无msg参数)
     * @param <T>
     * @return
     */
    public static <T> Result<T> error(){
        return new Result<T>("error");
    }

    private Result(T data) {
        this.code = 200;
        this.msg = "success";
        this.data = data;
    }

    private Result() {
        this.code = 200;
        this.msg = "success";
    }

    private Result(String msg) {
        this.code = 400;
        this.msg = msg;
    }

    public int getCode() {
        return code;
    }

    public String getMsg() {
        return msg;
    }

    public T getData() {
        return data;
    }

}

而控制层的getAll方法的返回类型等要改为:

@GetMapping("/getAll")
public Result getAll() {
	return Result.success(service.getAll());
}

此时用Postman访问http://localhost:8080/student/getAll得到的结果如下:
请添加图片描述
当然也可以在封装一个常用异常状态参数的类Error(静态异常可以根据项目自由定义)

public class Error {
    private int code;		// 状态码
    private String msg;		// 返回的信息

    private Error(int code, String msg) {
        this.code = code;
        this.msg = msg;
    }

    // 静态常用异常
    public static Error ERROR_1 = new Error(400,"异常类型一");
    public static Error ERROR_2 = new Error(500,"异常类型二");

    public int getCode() {
        return code;
    }

    public String getMsg() {
        return msg;
    }
}

然后在Result类中添加如下方法:

/**
 * 异常时候的调用(固定参数)
 * @param error
 * @param <T>
 * @return
 */
public static <T> Result<T> error(Error error){
    return new Result<T>(error);
}

private Result(Error error) {
    if (error == null){
        return ;
    }
    this.code = error.getCode();
    this.msg = error.getMsg();
}

使用:

/**
 * 测试定义参数异常
 * @return
 */
@GetMapping("/getError")
public Result getError() {
    return Result.error(ERROR_1);
}

访问http://localhost:8080/student/getError
请添加图片描述

  • 5
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值