项目结构如下
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;
}
}
大致用法如下