面向切面编程-AOP

类上需加注解

@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();执行目标方法

注意点

私有方法不能拦截

自有方法调用:this调用不能拦截,用self()代理调用可以拦截

  • 16
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

linsa_pursuer

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值