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

大致用法如下

相关推荐
qq_12498707535 分钟前
基于SSM的动物保护系统的设计与实现(源码+论文+部署+安装)
java·数据库·spring boot·毕业设计·ssm·计算机毕业设计
Coder_Boy_11 分钟前
基于SpringAI的在线考试系统-考试系统开发流程案例
java·数据库·人工智能·spring boot·后端
Mr_sun.12 分钟前
Day06——权限认证-项目集成
java
瑶山14 分钟前
Spring Cloud微服务搭建四、集成RocketMQ消息队列
java·spring cloud·微服务·rocketmq·dashboard
abluckyboy21 分钟前
Java 实现求 n 的 n^n 次方的最后一位数字
java·python·算法
2301_8187320623 分钟前
前端调用控制层接口,进不去,报错415,类型不匹配
java·spring boot·spring·tomcat·intellij-idea
2501_9419820537 分钟前
深度对比:Java、Go、Python 实现企微外部群推送,哪个效率更高?
java·golang·企业微信
马猴烧酒.1 小时前
【面试八股|JAVA多线程】JAVA多线程常考面试题详解
java·服务器·数据库
掘金者阿豪1 小时前
关系数据库迁移的“暗礁”:金仓数据库如何规避数据完整性与一致性风险
后端
ServBay2 小时前
一个下午,一台电脑,终结你 90% 的 Symfony 重复劳动
后端·php·symfony