0

I am using Spring AOP. I want my target method be matched only when invoked from a certain package. For example, let's assume my target method is com.domain.target.MyService.run(), and that it can be accessed from anywhere in my project. However, I want the pointcut to trigger only when the method is invoked from within a certain package, say com.domain.caller.*.

Is this something doable?

kriegaex
  • 63,017
  • 15
  • 111
  • 202
Tanvir
  • 542
  • 7
  • 16
  • Spring AOP works on the context of the bean method being executed. You will need to swtich to full blown AspectJ to achieve this . – R.G Nov 01 '21 at 03:01
  • Hi R.G, can you provide any further hint on which particular feature from AspectJ I should be looking into? Thanks – Tanvir Nov 01 '21 at 07:10
  • Unfortunately , I am not aware of AspectJ ( which is far more advanced than Spring AOP ) . Please wait for kriegaex or some other expert on this field to notice your question. You should be getting an answer soon. – R.G Nov 01 '21 at 07:15
  • 1
    Please read the answer I linked to when closing the question as a duplicate. You find information about both native AspectJ and the Spring AOP workaround using `ControlFlowPointcut`. I posted an extension for the latter which can also handle wildcards [here](https://stackoverflow.com/a/68434674/1082681). Also related is [this answer](https://stackoverflow.com/a/69567232/1082681) which also links to the other two, but is a bit less verbose, more of an overview. Feel free to open a new question if you have a concrete problem with any of the approaches discussed in my answers. – kriegaex Nov 01 '21 at 07:34
  • Thanks guys. This is what worked for me: `execution(* com.domain.target.MyService.run()) && cflowbelow(within(com.domain.caller.*))`. There's also an alternate approach that worked well (without embarking on native AspectJ dependency), and it's by using `new Throwable().getStackTrace()` and then inspecting the stacktrace. – Tanvir Nov 09 '21 at 19:51

1 Answers1

0

Yes, it's able to advice with package.

We could also match any type within the package or a sub-package.

@Pointcut("within(com.domain.caller)")
@Pointcut("within(com.domain.caller.*)")

You can find more detail:

https://www.baeldung.com/spring-aop-pointcut-tutorial

Huy Nguyen
  • 1,931
  • 1
  • 11
  • 11
  • This doesn't seem to be working. Note that my target method is in a package that is different from `com.domain.caller.*`. So basically the expression `@Pointcut("within(com.domain.caller.*) && execution(* com.domain.target.MyService.run())")` doesn't satisfy when `run()` is invoked. – Tanvir Nov 01 '21 at 07:09
  • Unfortunately, this answer is false, because `within` limits the target, not the caller. I.e., the two pointcuts you combined with `&&` are mutually exclusive and will match exactly nothing. So please disregard this answer. Sorry @huy, I know you meant to help, so thanks for trying. – kriegaex Nov 01 '21 at 07:23