本文记录下如何在工程中,配置后台的统一公共返回类,这样做目的是为了统一返回信息,方便项目进行管理。使用技术:SpringBoot+Swagger+Lombok
项目结构
具体过程如下,在response文件夹下分别建立 CustomizeResultCode 接口,枚举类ResultCode 实现CustomizeResultCode 接口和Result类:
1 配置自定义返回类接口,该接口中包含 错误状态码和错误信息
public interface CustomizeResultCode {
Integer getCode();
String getMessage();
}
2 配置返回实现类,注意这里是个枚举类,里面的编码仅供参考,可以自定义
public enum ResultCode implements CustomizeResultCode{
SUCCESS(200, "成功"),
ERROR(400,"错误失败"),
COMMON_FAIL(999, "失败"),
PARAM_NOT_VALID(1001, "参数无效"),
PARAM_IS_BLANK(1002, "参数为空"),
USER_NOT_LOGIN(2001, "用户未登录"),
USER_ACCOUNT_EXPIRED(2002, "账号已过期"),
USER_CREDENTIALS_ERROR(2003, "密码错误"),
ARITHMETIC_EXCEPTION(9001,"算数异常");
;
private Integer code;
private String message;
ResultCode(Integer code,String message){
this.code=code;
this.message=message;
}
@Override
public Integer getCode() {
return code;
}
@Override
public String getMessage() {
return message;
}
}
3 定义具体的返回类方法
@Data
public class Result {
@ApiModelProperty(value = "是否成功")
private Boolean success;
@ApiModelProperty (value= "返回码")
private Integer code;
@ApiModelProperty(value = "返回消息")
private String message;
@ApiModelProperty(value = "返回数据")
private Map<String,Object> data=new HashMap<>();
private Result(){
}
public static Result ok(){
Result result=new Result();
result.setSuccess(true);
result.setCode(ResultCode.SUCCESS.getCode());
result.setMessage(ResultCode.SUCCESS.getMessage());
return result;
}
public static Result error(){
Result result=new Result();
result.setSuccess(false);
result.setCode(ResultCode.ERROR.getCode());
result.setMessage(ResultCode.ERROR.getMessage());
return result;
}
public Result success(Boolean success){
this.setSuccess(success);
return this;
}
public Result message(String message){
this.setMessage(message);
return this;
}
public Result code(Integer code){
this.setCode(code);
return this;
}
public Result data(String key,Object value){
this.data.put(key,value);
return this;
}
public Result data(Map<String,Object>map){
this.setData(map);
return this;
}
}
统一返回类使用
Controller在下面的文件中
@RestController
@EnableAutoConfiguration
@RequestMapping("/system/info")
@Api(value = "系统模块",tags="系统接口")
public class DController {
@Autowired
private DService dService;
@GetMapping
@ApiOperation(value = "信息列表",notes = "查询所有信息")
public Result findDs(){
List<Doctordict>list=dService.list();
//链式编程
return Result.ok().data("users",list);
}
}
测试结果成功
到此这篇关于SpringBoot 统一公共返回类的实现的文章就介绍到这了,更多相关SpringBoot 统一公共返回类内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!