首页 > 解决方案 > Spring AOP:仅从另一个方法调用的捕获方法

问题描述

猜猜我有这些方法:

@Service
public class Service1 {
    private @Autowired Service2 service2;

    public void method1() {
        this.service2.method2();
    }
}

@Service2
public class Service2 {

    public void method2() {
        // Do something
    }

}

我想知道如何捕获Service2.method2()呼叫,当它被调用时Service1.method1())

有任何想法吗?

标签: springspring-bootspring-aop

解决方案


您可以在 Spring 中使用 AspectJ而不是 Spring AOP vis compile-time 或 load-time weaving,然后使用类似切入点

execution(* my.package.Service2.method2()) &&
  cflow(execution(* my.package.Service2.method2()))

或者,类似于@Damith所说,使用

  • Thread.currentThread().getStackTrace(),
  • new Exception().getStackTrace()或者
  • Java 9 StackWalkerAPI

为了手动导航调用堆栈并找到您正在寻找的信息。我的建议是使用 AspectJ,不仅因为它的优雅,还因为它的效率。


推荐阅读