Spring AOP中MethodBeforeAdvice、AfterReturningAdvice和MethodInterceptor的执行顺序

本文探讨了在Spring AOP中,当一个代理同时实现MethodBeforeAdvice、AfterReturningAdvice和MethodInterceptor接口时,不同配置下这三种Advice的执行顺序。实验结果表明,其执行顺序与XML文件中的定义顺序紧密相关。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在Spring 的AOP中,如果一个Proxy同时实现MethodBeforeAdvice、AfterReturningAdvice和MethodInterceptor接口,那么这三个Advice的执行顺序是什么样的呢?
经过试验,是和xml文件中的定义顺序有关的。
如果Proxy的接口实现定义为
     
         
            MethodBeforeAdvice
            AfterReturningAdvice
            MethodInterceptor
         
     
那么执行的结果是
MethodBeforeAdvice

MethodInterceptor: before call

Really method excuting

MethodInterceptor: after call

AfterReturningAdvice

也就是说,执行顺序是:MethodBeforeAdvice,MethodInterceptor的调用前的部分,目标方法,MethodInterceptor的调用后的部分,AfterReturningAdvice。

如果proxy的定义是
     
         
            MethodBeforeAdvice
            MethodInterceptor
            AfterReturningAdvice
         
     
执行的结果是
MethodBeforeAdvice

MethodInterceptor: before call

Really method excuting

AfterReturningAdvice

MethodInterceptor: after call
也就是说,执行的顺序是:MethodBeforeAdvice,MethodInterceptor的调用前的部分,目标方法,AfterReturningAdvice,MethodInterceptor的调用后的部分。

如果proxy的定义是
     
         
            MethodInterceptor
            MethodBeforeAdvice
            AfterReturningAdvice
         
     
执行的结果是:
MethodInterceptor: before call

MethodBeforeAdvice

Really method excuting

AfterReturningAdvice

MethodInterceptor: after call
也就是说,执行的顺序是:MethodInterceptor的调用前的部分,MethodBeforeAdvice,目标方法,AfterReturningAdvice,MethodInterceptor的调用后的部分。
以上的顺序是在springframework 1.2.5中测试的。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值