使用注解,返回统一数据格式

学习了《动态初始化类+参数泛型化+统一返回值》,这里面是用拼接的方式 返回统一格式的值,如果其它接口要添加了呢? 这时候考虑用注解的方式(使用aop的切面)进行处理。

目录

注解:

定义一个注解类ResultRegister

ResultRegistersAnalytic

实体类:

AppResult

 PageData 分页

 ResultCode 状态

统一返回值:

 ResultUtil 

异常类:

 AjaxResult 

 BusinessException 

 ErrorEnum 

 GlobalExceptionHandler

测试:

controller

请求结果:

总结:


注解:

定义一个注解类ResultRegister

import java.lang.annotation.*;

@Documented
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface ResultRegister {

}

ResultRegistersAnalytic

@Aspect
@Component
public class ResultRegistersAnalytic {

    private static final Logger logger = LoggerFactory.getLogger(ResultRegistersAnalyticComplex.class);

    @Resource
    private EntityManager entityManager;

    @Around("@annotation(com.spring.aop.annotate.ResultRegister)")
    private AppResult result(ProceedingJoinPoint pjp) throws Throwable {
        //获取方法参数值数组
        Object[] args = pjp.getArgs();
        //得到其方法签名
        MethodSignature methodSignature = (MethodSignature) pjp.getSignature();
        //获取方法参数类型数组
        Class[] paramTypeArray = methodSignature.getParameterTypes();
        if (EntityManager.class.isAssignableFrom(paramTypeArray[paramTypeArray.length - 1])) {
            //如果方法的参数列表最后一个参数是entityManager类型,则给其赋值
            args[args.length - 1] = entityManager;
        }
        logger.info("请求参数为{}",args);
        Object result = pjp.proceed(args);
        logger.info("响应结果为{}",result);
        return ResultUtil.success(result);
    }

}
 
  

@Around注解可以用来在调用一个具体方法前和调用后来完成一些具体的任务。

比如我们想在执行controller中方法前打印出请求参数,并在方法执行结束后来打印出响应值,统一处理值是应用Around调用后处理参数的功能;

这边使用简化的就行:

@Aspect
@Component
public class ResultRegistersAnalytic {

    @Around("@annotation(com.spring.aop.annotate.ResultRegister)")
    private static AppResult result(ProceedingJoinPoint pjp) throws Throwable {
        Object proceed = pjp.proceed();
        return ResultUtil.success(proceed);
    }

}
 
  
 
  

实体类:

AppResult

@Data
@ApiModel("统一请求返回体")
public class AppResult {

    @ApiModelProperty("返回的状态码,0为正常")
    private int status;

    @ApiModelProperty("错误消息")
    private String message;

    @ApiModelProperty("返回值")
    private T data;

    @ApiModelProperty("返回的数据总数,分页时,返回实际数量")
    private long total;
}

 PageData 分页

@Data
public class PageData {
    private long total;
    private List data;
}

 ResultCode 状态

/**
 * 错误码
 */
public enum ResultCode {

    /**
     * 成功
     */
    SUCCESS(0, "success"),

    /**
     * 未知错误
     */
    UNKNOWN_ERROR(400, "unkonwn error");


    /**
     * 结果码
     */
    private Integer code;

    /**
     * 结果码描述
     */
    private String msg;


    ResultCode(Integer code, String msg) {
        this.code = code;
        this.msg = msg;
    }

    public Integer getCode() {
        return code;
    }

    public String getMsg() {
        return msg;
    }
}

统一返回值:

 ResultUtil 

public final class ResultUtil {
    public static AppResult success() {
        return success(true);
    }

    public static  AppResult success(T object) {
        AppResult result = new AppResult<>();
        result.setStatus(0);
        result.setData(object);
        long total;
        try {
            total = CollectionUtils.size(object);
        } catch (IllegalArgumentException ex) {
            total = 0;
        }
        result.setTotal(total);
        return result;
    }

    // 处理带分页的
    public static  AppResult> success(PageData object) {
        AppResult> result = new AppResult<>();
        result.setStatus(0);
        result.setData(object.getData());
        result.setTotal(object.getTotal());
        return result;
    }

    public static  AppResult success(Optional object) {
        return success(object.orElse(null));
    }

    public static  AppResult success(Optional object, Class writerView) {
        return success(object.orElse(null), writerView);
    }

    public static  AppResult success(T object, Class writerView) {
        ObjectMapper mapper = new ObjectMapper();
        try {
            String jsonString = mapper.writerWithView(writerView).writeValueAsString(object);
            T t = JSONObject.parseObject(jsonString, new TypeReference() {
            });
            return success(t);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            return error(500, "json转换错误");
        }
    }

    public static  AppResult error(Integer status, String message) {
        AppResult result = new AppResult<>();
        result.setStatus(status);
        result.setMessage(message);
        return result;
    }

    public static  AppResult error(ResultCode resultCode) {
        AppResult result = new AppResult<>();
        result.setStatus(resultCode.getCode());
        result.setMessage(resultCode.getMsg());
        return result;
    }
}

异常类:

 AjaxResult 

@Data
@NoArgsConstructor(access = AccessLevel.PUBLIC)
@AllArgsConstructor(access = AccessLevel.PUBLIC)
@ApiModel(value = "异常的返回值")
public class AjaxResult {

    @ApiModelProperty("是否成功")
    private Boolean success;

    @ApiModelProperty("状态码")
    private Integer code;

    @ApiModelProperty("提示信息")
    private String msg;

    @ApiModelProperty("数据")
    private Object data;

    //自定义异常返回的结果
    public static AjaxResult defineError(BusinessException de){
        AjaxResult result = new AjaxResult();
        result.setSuccess(false);
        result.setCode(de.getErrorCode());
        result.setMsg(de.getErrorMsg());
        result.setData(null);
        return result;
    }
    //其他异常处理方法返回的结果
    public static AjaxResult otherError(ErrorEnum errorEnum){
        AjaxResult result = new AjaxResult();
        result.setMsg(errorEnum.getErrorMsg());
        result.setCode(errorEnum.getErrorCode());
        result.setSuccess(false);
        result.setData(null);
        return result;
    }


}

 BusinessException 

@Data
@ApiModel(value = "异常信息")
public class BusinessException extends RuntimeException {
    private static final long serialVersionUID = 1L;

    @ApiModelProperty("错误状态码")
    private Integer errorCode;

    @ApiModelProperty("错误提示")
    private String errorMsg;

}

 ErrorEnum 

public enum ErrorEnum {
    // 数据操作错误定义
    SUCCESS(200, "成功"),
    NO_PERMISSION(403,"你没得权限"),
    NO_AUTH(401,"未登录"),
    NOT_FOUND(404, "未找到该资源!"),
    INTERNAL_SERVER_ERROR(500, "服务器异常请联系管理员"),
    ;

    /** 错误码 */
    private Integer errorCode;

    /** 错误信息 */
    private String errorMsg;

    ErrorEnum(Integer errorCode, String errorMsg) {
        this.errorCode = errorCode;
        this.errorMsg = errorMsg;
    }

    public Integer getErrorCode() {
        return errorCode;
    }

    public String getErrorMsg() {
        return errorMsg;
    }
}

 GlobalExceptionHandler

/**
 * 全局异常处理器
 *
 */
@RestControllerAdvice
public class GlobalExceptionHandler
{
    private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);


    /**
     * 处理自定义异常
     *
     */
    @ExceptionHandler(value = BusinessException.class)
    public AjaxResult bizExceptionHandler(BusinessException e) {
        log.error(e.getMessage(), e);
        return AjaxResult.defineError(e);
    }

    /**
     *处理其他异常
     *
     */
    @ExceptionHandler(value = Exception.class)
    public AjaxResult exceptionHandler( Exception e) {
        log.error(e.getMessage(), e);
        return AjaxResult.otherError(ErrorEnum.INTERNAL_SERVER_ERROR);

    }

}

测试:

controller

@Slf4j
@Controller
@RequestMapping("/aop")
public class AopController {

    @ResponseBody
    @ResultRegister
    @GetMapping(value = "/getAopInfo")
    public Object configureTasks() {
        return "I will do it";
    }


    @ResponseBody
    @ResultRegister
    @PostMapping(value = "/postAopInfo")
    public Object getAops(@RequestBody JSONObject json) {
        System.out.println(json.toJSONString());
        json.put("return", "do you best!");
        return json;
    }
}

启动后使用postman,进行请求:

请求结果:

get:http://localhost:8080/aop/getAopInfo

返回值:

{
    "status": 0,
    "message": null,
    "data": {
        "status": 0,
        "message": null,
        "data": "I will do it",
        "total": 0
    },
    "total": 0
}

post: http://localhost:8080/aop/postAopInfo

param: 

{
    "make": "feng"
}

返回值:

{
    "status": 0,
    "message": null,
    "data": {
        "status": 0,
        "message": null,
        "data": {
            "make": "feng",
            "return": "do you best!"
        },
        "total": 2
    },
    "total": 0
}

总结:

       注解主要是使用@Around进行处理,这样在使用的时候,在需要返回统一格式的数据中添加相应的注解可以了。

你可能感兴趣的:(java,java,around,统一格式返回)