读懂Spring AOP中通知的执行原理

前言

这个代理类是AOP基于JDK动态代理生成的,当使用代理类调用目标方法时,会执行到org.springframework.aop.framework.JdkDynamicAopProxy#invoke方法中去,后面的调用链也在这里面。

定义一个切面

切面包含了环绕通知(前)、前置通知、增强方法、环绕通知(后、后置通知、带返回值后置通知、异常通知

/**
 * 增强计算器的切面
 */
@Component
@Aspect
public class JisuanqiAspect {

    //AOP功能==》引入方式的使用

  /*  @DeclareParents(value = "yuanma.leiqiang.aop.JiSuanQiImpl",
            defaultImpl = YinruImpl.class
    )
    public static Yinru yinru;*/



    //各种通知的使用↓
    @Pointcut("execution(* com.redis.aop..*(..))")
    public void pointCut() {}

    @Before(value = "pointCut()")
    public void before(JoinPoint joinPoint) throws Exception{
        String name = joinPoint.getSignature().getName();
        System.out.println("Before增强了方法"+ name);

    }

    @After(value = "pointCut()")
    public void after(JoinPoint joinPoint) throws Exception{
        String name = joinPoint.getSignature().getName();
        System.out.println("无返回值After增强了方法"+ name);

    }

    @AfterReturning(value = "pointCut()", returning = "result")
    public void afterReturning(JoinPoint joinPoint, Object result) throws Exception{
        String name = joinPoint.getSignature().getName();
        System.out.println("带返回值After增强了方法"+ name + "结果为"+result);

    }

    @AfterThrowing(value = "pointCut()")
    public void afterThrowing(JoinPoint joinPoint) throws Exception{
        String name = joinPoint.getSignature().getName();
        System.out.println("方法出现了异常"+ name);

    }

    @Around(value = "pointCut()")
    public Object around(ProceedingJoinPoint pjp) throws Throwable{
        String name = pjp.getSignature().getName();
        System.out.println("环绕通知=>方法执行前"+ name);

        Object object = pjp.proceed(pjp.getArgs());//执行我们的方法

        System.out.println("环绕通知=>方法执行后"+ name);
        return object;
    }
}

执行结果

在这里插入图片描述
上图中有3张图,上面2张为控制台打印的AOP各种类型通知的执行顺序
上两图介绍
图1为执行了异常通知的打印结果:环绕通知(前)→前置通知→增强方法→后置通知→异常通知
图2为正常的结果:环绕通知(前)→前置通知→增强方法→环绕通知(后)→后置通知→带返回值后置通知
可以看出当出现异常后,那种通知是不会被执行的
第三张图
这个图为AOP生成代理类后,使用代理类调用目标方法时执行通知的集合,就是chain集合中的通知会被递归调用,这些方法中看名字就知道是AOP对各个通知方法的调用;

图解通知的执行流程

在这里插入图片描述

将图片中的代码归纳在一起


    public static void main(String[] args) {
        MethodInvocation oldInvocation = invocation.get();
        invocation.set(mi);
        try {
            //ExposeInvocationInterceptor.invoke AOP内置的一个通知,可以不用看


            try {
                //AspectJAfterThrowingAdvice.invoke 这是异常通知,可以看就是一个try/catch,也就是将后面的执行逻辑全部包含,所以异常通知能捕获异常呢

                Object retVal;
                //AfterReturningAdviceInterceptor.invoke 带返回值的后置通知,可以看到这里它定义了返回值接收参数

                try {
                    //AspectJAfterAdvice.invoke 无返回值的后置通知,可以看得出,为啥就算目标方法异常了,后置通知还是会执行,因为后置通知的调用在finally中

                    String name = pjp.getSignature().getName();
                    System.out.println("环绕通知=>方法执行前" + name);
                    //执行环绕通知,这里环绕通知会跳转到自己定义的方法中去执行proceed()这个递归方法,在其他的通知类型中proceed()这个方法都是由AOP去执行的,在环绕通知中,是需要我们自己去执行

                    this.advice.before(mi.getMethod(), mi.getArguments(), mi.getThis());
                    //执行前置通知MethodBeforeAdviceInterceptor.invoke 继续递归

                    if (this.currentInterceptorIndex == this.interceptorsAndDynamicMethodMatchers.size() - 1) {
                        return invokeJoinpoint();
                    }
                    //最终执行连接点,就我们的目标方法ReflectiveMethodInvocation.proceed

                    //最终执行连接点,就我们的目标方
                    //执行前置通知

                    //执行环绕通知,这里环绕通知会跳转到自己定义的方法中去执行
                    System.out.println("环绕通知=>方法执行后" + name);

                    //AspectJAfterAdvice.invoke
                } finally {
                    invokeAdviceMethod(getJoinPointMatch(), null, null);
                }

                //AfterReturningAdviceInterceptor.invoke
                this.advice.afterReturning(retVal, mi.getMethod(), mi.getArguments(), mi.getThis());
                return retVal;

                //AspectJAfterThrowingAdvice.invoke
            } catch (Throwable ex) {
                if (shouldInvokeOnThrowing(ex)) {
                    invokeAdviceMethod(getJoinPointMatch(), null, ex);
                }
                throw ex;
            }


            //ExposeInvocationInterceptor.invoke AOP内置的一个通知
        } finally {
            invocation.set(oldInvocation);
        }
    }
    
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

IT界的老菜鸟

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

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

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

打赏作者

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

抵扣说明:

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

余额充值