Search code examples
javaspringspring-bootaopaspectj

How to define a Pointcut to pick out all methods invoked by the specified method?


Is there any way to define a pointcut in AspectJ that would pick out each method directly executed by a specified method?

For example if there is a parentMethod() in classA that looks like:

public void parentMethod() {
    classB.methodX();
    classC.methodY();
}

I want to define a pointcut that uses just the information about parentMethod to pick out whenever its invoked methods, methodX() and methodY(), are executed. Is there a way to achieve this using AspectJ pointcuts?


Solution

  • I think we are not talking about inheritance, so you should not call it a "parent method". You simply mean a method calling other methods, do you not? Anyway, concerning your question:

    With Spring AOP you have limited means of expressing control flow pointcuts, compared to native AspectJ's cflow() and cflowbelow() pointcuts. In your case and if you want to stick with proxy-based Spring AOP, a ControlFlowPointcut might be enough, because you do not need any method name patterns but seem to have a fixed method name as your target. For more information, see:

    • Section "update 2" of this answer for basic pointers to resources concerning ControlFlowPointcut.
    • This answer, if you want to match method patterns with a custom MultiMethodControlFlowPointcut (currently still unsupported by Spring out of the box).
    • Spring manual chapter "Using AspectJ with Spring Applications" explains how to configure Spring to use native AspectJ via load-time weaving (LTW).
    • If you decide to go the native AspectJ LTW way, the AspectJ manual section about control-flow-based pointcuts briefly explains cflow and cflowbelow.