栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

JavaWeb-SpringBoot项目通用响应的设计

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

JavaWeb-SpringBoot项目通用响应的设计

  • 依赖:lombok

	org.projectlombok
	lombok
	true

项目common结构:

CommonResponse写法

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.Getter;

import java.io.Serializable;

@Getter
@JsonInclude(JsonInclude.Include.NON_NULL)
public class CommonResponse implements Serializable {

    private int status;
    private String msg;
    private T data;

    private CommonResponse(int status){
        this.status=status;
    }
    private CommonResponse(int status,String msg){
        this.status=status;
        this.msg=msg;
    }
    private CommonResponse(int status,String msg,T data){
        this.status=status;
        this.msg=msg;
        this.data=data;
    }
    private CommonResponse(int status,T data){
        this.status=status;
        this.data=data;
    }

    @JsonIgnore
    public boolean isSuccess(){
        return this.status == ResponseCode.SUCCESS.getCode();
    }
    public static  CommonResponse  createForSuccess(){
        return new CommonResponse(ResponseCode.SUCCESS.getCode());
    }
    public static  CommonResponse  createForSuccess(T data){
        return new CommonResponse(ResponseCode.SUCCESS.getCode(),data);
    }
    public static  CommonResponse  createForSuccessMessage(String msg){
        return new CommonResponse(ResponseCode.SUCCESS.getCode(),msg);
    }
    public static  CommonResponse  createForSuccess(String msg,T data){
        return new CommonResponse(ResponseCode.SUCCESS.getCode(),msg,data);
    }
    public static  CommonResponse  createForError(){
        return new CommonResponse(ResponseCode.ERROR.getCode(),ResponseCode.ERROR.getDescription());
    }
    public static  CommonResponse  createForError(String msg){
        return new CommonResponse(ResponseCode.ERROR.getCode(),msg);
    }
    public static  CommonResponse  createForError(int code,String msg){
        return new CommonResponse(code,msg);
    }
}

ResponseCode(枚举)的写法

import lombok.Getter;

@Getter
public enum ResponseCode {
    SUCCESS(0,"SUCCESS"),
    ERROR(1,"ERROR"),
    NEED_LOGIN(10,"NEED_LOGIN"),
    ILLEGAL_ARGUMENT(2,"ILLEGAL_ARGUMENT");

    private final int code;
    private final String description;

    ResponseCode(int code,String description){
        this.code=code;
        this.description = description;
    }

}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/340102.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号