1

Guess I have these methods:

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

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

@Service2
public class Service2 {

    public void method2() {
        // Do something
    }

}

I'd like to know how to capture Service2.method2() call, when it's called from Service1.method1()).

Any ideas?

Jordi
  • 20,868
  • 39
  • 149
  • 333
  • what do you mean by capture? – Pavan Andhukuri Oct 25 '18 at 06:55
  • How to create a pointcut – Jordi Oct 25 '18 at 06:55
  • I think the AspectJ `cflow` pointcut designator may let you do what you want - inject code on calls to method2 from method1 - but I haven't done this myself (yet :-p). You would need full AspectJ, not just the subset that is supported directly by Spring aspects. – moilejter Oct 25 '18 at 07:25
  • I guess you need something like : Java 9 - JEP 259: Stack-Walking API walk through the answers of this question. https://stackoverflow.com/questions/421280/how-do-i-find-the-caller-of-a-method-using-stacktrace-or-reflection. you will find it – Damith Oct 25 '18 at 08:31
  • @Jordi answered , Hope it helps :) – Mohit Sharma Oct 25 '18 at 10:37

1 Answers1

1

You can either use AspectJ from within Spring instead of Spring AOP vis compile-time or load-time weaving and then a pointcut like

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

or, similar to what @Damith said, use either of

  • Thread.currentThread().getStackTrace(),
  • new Exception().getStackTrace() or
  • the Java 9 StackWalker API

in order to navigate the call stack manually and find the information you are looking for. My suggestion is to use AspectJ, not just because of its elegance but also because of its efficiency.

kriegaex
  • 63,017
  • 15
  • 111
  • 202