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;
    }
}

大致用法如下

相关推荐
摸鱼的春哥2 分钟前
Agent教程15:认识LangChain(中),状态机思维
前端·javascript·后端
Seven976 分钟前
剑指offer-80、⼆叉树中和为某⼀值的路径(二)
java
风象南7 小时前
我把大脑开源给了AI
人工智能·后端
橙序员小站11 小时前
Agent Skill 是什么?一文讲透 Agent Skill 的设计与实现
前端·后端
怒放吧德德11 小时前
Netty 4.2 入门指南:从概念到第一个程序
java·后端·netty
雨中飘荡的记忆13 小时前
大流量下库存扣减的数据库瓶颈:Redis分片缓存解决方案
java·redis·后端
开心就好202514 小时前
UniApp开发应用多平台上架全流程:H5小程序iOS和Android
后端·ios
悟空码字15 小时前
告别“屎山代码”:AI 代码整洁器让老项目重获新生
后端·aigc·ai编程
小码哥_常15 小时前
大厂不宠@Transactional,背后藏着啥秘密?
后端
奋斗小强15 小时前
内存危机突围战:从原理辨析到线上实战,彻底搞懂 OOM 与内存泄漏
后端