类上需加注解
@Aspect @Component
切入点
方法
@Pointcut("execution(* com.LogTest.test(..))") public void test() { }
注解
匹配有指定注解的方法(注解作用在方法上面)
@Pointcut("@annotation(com.AsyncAnnotation)") public void asyncLogAspect() { }
匹配包含某个注解的类(注解作用在类上面)
用于拦截所有继承接口的类
@Pointcut("@within(com.Job)") public void jobAspect() {}
匹配目标对象有指定注解的类(注解作用在类上面)
@Pointcut("@target(com.Job)") public void jobAspect() {}
符号
PointCut中可以使用&&、||、! 运算符
@Pointcut("@annotation(com.AsyncAnnotation) || execution(* com.LogTest.test(..))")
@Pointcut("test() || asyncLogAspect()")
通知
@Before: 前置通知,在方法执行之前执行。
@Aspect @Component @Slf4j public class TestAop { /** * 切入点 */ @Pointcut("execution(* com.LogTest.test(..))") public void test() { } @Before("test()") public void doBefore(JoinPoint joinPoint) { Object[] args = joinPoint.getArgs(); // 参数 Long id = (Long) args[0]; // 第一个参数 } }
@After:后置通知,在方法执行后执行。
@After("execution(* com.LogTest.test(..))") public void doAfter(JoinPoint joinPoint)
@AfterReturning: 返回通知,在方法返回结果之后执行。
@AfterReturning(returning = "ret", pointcut = "asyncLogAspect()") public void doAfterReturning(Object ret)
@AfterThrowing:异常通知,在方法抛出异常之后执行。
@AfterThrowing(pointcut = "asyncLogAspect()",throwing = "ex") public void doAfterThrowable(Throwable ex)
@Around:环绕通知,围绕着方法执行。
@Around("asyncLogAspect() && @annotation(asyncAnnotation)") public Object doAround(ProceedingJoinPoint pjp, AsyncAnnotation asyncAnnotation) throws Throwable
pjp.proceed();执行目标方法