返回结果统一转换
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;
@RestControllerAdvice(basePackages = "com.wuxian")
public class ResponseAdvisor implements ResponseBodyAdvice<Object> {
@Override
public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
return true;
}
@Override
public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
if (body instanceof Result){
return body;
}
if (body instanceof Boolean){
boolean result = (boolean)body;
return new BaseResponse<Boolean>(result);
}
if (body instanceof PageVO){
return new BaseResponse<>(body);
}
if (body instanceof ExceptionResponse){
return new BaseResponse<>(400,((ExceptionResponse)body).getMsg());
}
return new BaseResponse<>(body);
}
}
import com.fasterxml.jackson.annotation.JsonInclude;
@Data
@JsonInclude(JsonInclude.Include.NON_NULL)
public class BaseResponse<D> implements Serializable {
private static final long serialVersionUID = -2145852753254617071L;
private boolean success;
private String message;
private int code;
private D data;
public BaseResponse() {
this.code = 200;
this.message = "success";
this.success = true;
}
public BaseResponse(D data){
this();
this.data = data;
}
public BaseResponse(boolean success){
this();
this.success = success;
if(success == false){
this.message = "操作失败";
this.code = 300;
}
}
public BaseResponse(boolean success,String msg){
this(success);
this.message = msg;
}
public BaseResponse(int code,String msg){
this(false,msg);
this.code = code;
}
}
@Data
public class Result {
private int status;
private String desc;
private Object data;
private String token;
}
@Data
public class ExceptionResponse{
private String msg;
public ExceptionResponse(String msg){
this.msg = msg;
}
}