SpringBoot自定义Result类替换Map<String,Object>

项目结构如下

Result类

复制代码
package cn.ryanfan.virtulab_back.common.result;

import io.swagger.annotations.ApiModelProperty;
import lombok.Data;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

@Data
public class Result implements Serializable {
    @ApiModelProperty(value = "是否操作成功")
    private boolean success;
    @ApiModelProperty(value = "状态码")
    private Integer code;
    @ApiModelProperty(value = "操作信息")
    private String message;
    @ApiModelProperty(value = " 操作数据")
    private Map<String,Object> data = new HashMap<>();

    public static Result ok(){
        Result result = new Result();
        result.setSuccess(true);
        result.setCode(ResultInfo.SUCCESS.getCode());
        result.setMessage(ResultInfo.SUCCESS.getMessage());
        return result;
    }
    public  static Result error(){
        Result result=new Result();
        result.setSuccess(false);
        result.setCode(ResultInfo.ERROR.getCode());
        result.setMessage(ResultInfo.ERROR.getMessage());
        return  result;
    }


    public Result code(Integer code){
        this.setCode(code);
        return  this;
    }

    public Result message(String message){
        this.setMessage(message);
        return  this;
    }

    public Result data(String key,Object data){
        this.data.put(key, data);
        return  this;
    }
}

IResult接口

复制代码
package cn.ryanfan.virtulab_back.common.result;

public interface IResult {
    Integer getCode();
    String getMessage();
}

ResultInfo枚举类

复制代码
package cn.ryanfan.virtulab_back.common.result;

public enum ResultInfo implements IResult{
    SUCCESS(200,"操作成功"),
    ERROR(400,"操作失败"),
    NOT_FOUND(404,"没有找到"),
    ;
    private  Integer code;
    private  String message;

    ResultInfo(Integer code,String message){
        this.code=code;
        this.message=message;
    }
    @Override
    public Integer getCode() {
        return code;
    }

    @Override
    public String getMessage() {
        return message;
    }
}

大致用法如下

相关推荐
uzong6 小时前
面试官:Redis中的 16 库同时发送命令,服务端是串行执行还是并行执行
后端·面试·架构
呼啦啦啦啦啦啦啦啦6 小时前
常见的排序算法
java·算法·排序算法
anlogic6 小时前
Java基础 8.18
java·开发语言
追逐时光者7 小时前
.NET 使用 MethodTimer 进行运行耗时统计提升代码的整洁性与可维护性!
后端·.net
练习时长一年7 小时前
AopAutoConfiguration源码阅读
java·spring boot·intellij-idea
你的人类朋友8 小时前
【Node.js】什么是Node.js
javascript·后端·node.js
源码宝8 小时前
【智慧工地源码】智慧工地云平台系统,涵盖安全、质量、环境、人员和设备五大管理模块,实现实时监控、智能预警和数据分析。
java·大数据·spring cloud·数据分析·源码·智慧工地·云平台
David爱编程9 小时前
面试必问!线程生命周期与状态转换详解
java·后端
LKAI.10 小时前
传统方式部署(RuoYi-Cloud)微服务
java·linux·前端·后端·微服务·node.js·ruoyi
HeyZoeHey10 小时前
Mybatis执行sql流程(一)
java·sql·mybatis