实现对指定接口进行拦截,横向插入自己的自定义逻辑内容
1. 创建一个自定义注解当做切面
可以按自己的需要创建多个参数使用,我这里为了举例子就写了一个。
package com.a.b.common.utils.operationrecord;
import java.lang.annotation.*;
@Target({ElementType.PARAMETER, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Operation {
String operationType() default "";
}
2. 创建切面,对拦截(添加了注解的接口)到的内容进行处理
可以通过方法获取请求参数、返回参数、和自定义注解的参数,这里我就不写这么多了,只写了一个获取自定义注解的参数。
package com.a.b.common.utils.operationrecord;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import java.lang.annotation.Annotation;
/**
* @program: h6dp-parent
* @description:
* @author:
* @create: 2023-02-08 14:23
**/
@Aspect
@Component
public class OperationAspect {
//设置切点
@Pointcut("@annotation(Operation)")
public void operationCut() {
}
/**
* 处理完请求后执行
*
* @param joinPoint 切点
* @param jsonResult 接口返回值
*/
@AfterReturning(pointcut = "operationCut()", returning = "jsonResult")
public void doAfterReturning(JoinPoint joinPoint, Object jsonResult) {
//获取自定义注解的值
MethodSignature signature = (MethodSignature)joinPoint.getSignature();
Operation operation = signature.getMethod().getDeclaredAnnotation(Operation.class);
System.out.println("operationType " + operation.operationType());
System.out.println("joinPoint " + jsonResult);
}
@Around(value = "operationCut()")
public void doAround(ProceedingJoinPoint joinPoint) {
System.out.println("joinPoint " + joinPoint);
}
/**
* 拦截异常操作
*
* @param joinPoint 切点
* @param e 异常
*/
@AfterThrowing(pointcut = "operationCut()", throwing = "e")
public void doAfterThrowing(JoinPoint joinPoint, Exception e) {
}
}
3. 配置目标,在想要拦截的接口上添加注解
配置目标,在需要拦截的接口上写上刚才的自定义注解,整个流程就算完成了,之后运行项目看