1、首先定義常用返回枚舉:(可以根據(jù)自己系統(tǒng)的需求自定義)
public enum CommomCode {
SUCCESS(200,"成功"),
? ? INNER_ERROR(500,"服務(wù)器內(nèi)部錯(cuò)誤"),
? ? OUT_ERROR(400,"外部服務(wù)器錯(cuò)誤"),
? ? NO_AUTHORITY(403,"認(rèn)證失敗");
? ? private int code;
? ? private Stringmessage;
? ? CommomCode(int code,String message){
this.code=code;
? ? ? ? this.message=message;
? ? }
public int getCode() {
return code;
? ? }
public void setCode(int code) {
this.code = code;
? ? }
public StringgetMessage() {
return message;
? ? }
public void setMessage(String message) {
this.message = message;
? ? }
}
2伯病、利用泛型定義公共返回類(避免弱類型返回)
@Setter
@Getter
/**
* 公共返回結(jié)果
*/
public class CommonResultimplements Serializable {
/**
? ? * 返回信息
? ? */
? ? private Stringmessage;
? ? /**
? ? * 返回狀態(tài)碼
? ? */
? ? private int code;
? ? /**
? ? * 返回值
? ? */
? ? private T data;
? ? /**
? ? * 定義無數(shù)據(jù)返回成功結(jié)果
? ? * @return
? ? */
? ? public static CommonResultsuccess(){
CommonResult CommonResult =new CommonResult();
? ? ? ? CommonResult.setCode(CommomCode.SUCCESS.getCode());
? ? ? ? CommonResult.setMessage(CommomCode.SUCCESS.getMessage());
? ? ? ? return CommonResult;
? ? }
/**
? ? * 定義系統(tǒng)內(nèi)部無數(shù)據(jù)返回錯(cuò)誤結(jié)果
? ? * @return
? ? */
? ? public static CommonResultinnerError(){
CommonResult CommonResult =new CommonResult();
? ? ? ? CommonResult.setCode(CommomCode.INNER_ERROR.getCode());
? ? ? ? CommonResult.setMessage(CommomCode.INNER_ERROR.getMessage());
? ? ? ? return CommonResult;
? ? }
/**
? ? * 定義系統(tǒng)外部無數(shù)據(jù)返回錯(cuò)誤結(jié)果
? ? * @return
? ? */
? ? public static CommonResultoutError(){
CommonResult CommonResult =new CommonResult();
? ? ? ? CommonResult.setCode(CommomCode.OUT_ERROR.getCode());
? ? ? ? CommonResult.setMessage(CommomCode.OUT_ERROR.getMessage());
? ? ? ? return CommonResult;
? ? }
/**
? ? * 定義系統(tǒng)外部無數(shù)據(jù)返回錯(cuò)誤結(jié)果
? ? * @return
? ? */
? ? public static CommonResultauthorityError(){
CommonResult CommonResult =new CommonResult();
? ? ? ? CommonResult.setCode(CommomCode.NO_AUTHORITY.getCode());
? ? ? ? CommonResult.setMessage(CommomCode.NO_AUTHORITY.getMessage());
? ? ? ? return CommonResult;
? ? }
/**
? ? * 自定義成功返回值
? ? * @param data
? ? */
? ? public static CommonResultsuccessWithData(T data){
CommonResult CommonResult =new CommonResult();
? ? ? ? CommonResult.setCode(CommomCode.SUCCESS.getCode());
? ? ? ? CommonResult.setMessage(CommomCode.SUCCESS.getMessage());
? ? ? ? CommonResult.setData(data);
? ? ? ? return CommonResult;
? ? }
/**
? ? * 自定義返回值
? ? */
? ? public static CommonResultresult(int code,String message,T data){
CommonResult CommonResult =new CommonResult();
? ? ? ? CommonResult.setCode(code);
? ? ? ? CommonResult.setMessage(message);
? ? ? ? CommonResult.setData(data);
? ? ? ? return CommonResult;
? ? }
}
3造烁、使用實(shí)例:在controller加上泛型
4、與swagger集成效果午笛,這樣就可以清晰的看到返參的值