spring boot返回統一處理
@SuppressWarnings({ "rawtypes" })
@RestControllerAdvice("com.wuxin")
public class MyResponseBodyAdvice implements ResponseBodyAdvice<Object> {
private static Set<String> excludeSetClass = new HashSet<String>();
private static Set<String> excludeSetMethod = new HashSet<String>();
static {
excludeSetMethod.add("com.wuxin.action.wxmini.WechatPayAction.payNotify");
excludeSetMethod.add("com.wuxin.action.wxmini.WechatPayAction.refundNotify");
}
@Override
public boolean supports(MethodParameter returnType, Class converterType) {
if (excludeSetClass.contains(returnType.getMethod().getDeclaringClass().getName())) {
return false;
}
String method = returnType.getMethod().getDeclaringClass().getName() + "." + returnType.getMethod().getName();
if (excludeSetMethod.contains(method)) {
return false;
}
return true;
}
@Override
public Object beforeBodyWrite(Object returnValue, MethodParameter methodParameter, MediaType selectedContentType,
Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
if (ResData.class.isInstance(returnValue)) {
return returnValue;
} else if (String.class.isInstance(returnValue)) {
return JsonUtil.toJSon(ResData.ok(returnValue));
}
return ResData.ok(returnValue);
}
}
@ApiModel("接口統一返回的對象")
public class ResData {
@ApiModelProperty("響應業務狀態碼0:成功,非0:失敗")
private int code;
@ApiModelProperty("調用接口失敗時返回的錯誤信息")
private String msg;
@ApiModelProperty("調用接口成功時返回的數據")
private Object data;
public ResData() {
}
public ResData(int code, String msg) {
this.code = code;
this.msg = msg;
}
public static ResData ok(Object data) {
ResData res = new ResData(0, "success");
res.setData(data);
return res;
}
public static ResData fail(String msg) {
ResData res = new ResData(-1, msg);
return res;
}
public static ResData fail(int code, String msg) {
ResData res = new ResData(code, msg);
return res;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
@Override
public String toString() {
return "ResData [code=" + code + ", msg=" + msg + ", data=" + data + "]";
}
}