Spring使用AOP完成统一结果封装
起因:自己写项目的时候忍受不了每个方法都要写一个retrun Result.success();
和 retrun Result.error();
,同时想到项目运行时异常的统一捕捉处理,于是我就在想有没有一种方法能够快捷有效的实现统一返回结果格式的方法。同时也能够比较方便的设置各种参数方便使用,于是我就想到AOP。
Demo实现
引入依赖
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
自定义注解(NoResult.java 使用此注解的method,将不会封装返回结果)
/**
* @interface自定义注解
* @Target: 注解的作用目标 PARAMETER:方法参数 METHOD:方法 TYPE:类、接口
*
* @Retention:注解的保留位置 RUNTIME 种类型的Annotations将被JVM保留,
*
* 能在运行时被JVM或其他使用反射机制的代码所读取和使用
*/
@Documented
@Target({
ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface NoResult {
}
ResultCode.class 用于定义Reponses返回码
public enum ResultCode {
SUCCESS(0, "操作成功", ""),
ERROR(1, "操作失败", "");
private final int code;
/**
* 状态码信息
*/
private final String message;
/**
* 状态码描述(详情)
*/
private final String description;
ResultCode(int code, String message, String description) {
this.code = code;
this.message = message;
this.description = description;
}
public int getCode() {
return code;
}
public String getMessage()