Spring的AOP子调用拦截问题

本文讨论了Spring AOP无法拦截内部子调用的问题,解释了原因并提出了两种应对策略:代码重构以避免自调用,或者将业务逻辑绑定到Spring AOP上下文。还提及AspectJ作为非代理基于的AOP框架,不存此问题。

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

        这两天需要用spring的aop处理些问题,发现使用spring的aop不能拦截子调用的情况。spring官方文档在Understanding AOP proxies这节中也提到了这个问题。
         The key thing to understand here is that the client code inside the main(..) of the Main class has a reference to the proxy. This means that method calls on that object reference will be calls on the proxy, and as such the proxy will be able to delegate to all of the interceptors (advice) that are relevant to that particular method call. However, once the call has finally reached the target object, the SimplePojo reference in this case, any method calls that it may make on itself, such as this.bar() or this.foo(), are going to be invoked against the this reference, and not the proxy. This has important implications. It means that self-invocation is not going to result in the advice associated with a method invocation getting a chance to execute.
        Okay, so what is to be done about this? The best approach (the term best is used loosely here) is to refactor your code such that the self-invocation does not happen. For sure, this does entail some work on your part, but it is the best, least-invasive approach. The next approach is absolutely horrendous, and I am almost reticent to point it out precisely because it is so horrendous. You can (choke!) totally tie the logic within your class to Spring AOP by doing this:

public class SimplePojo implements Pojo {
      public void foo() {
            // this works, but... gah!
            ((Pojo) AopContext.currentProxy()).bar();
      }
      public void bar() {
             // some logic...
       }
}

Finally, it must be noted that AspectJ does not have this self-invocation issue because it is not a proxy-based AOP framework.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值