Search code examples
javaspringaopspring-aop

AOP, how to intercept calls to a given class only when made directly from a package X


I would like to intercept all calls made to a certain object: org.springframework.data.redis.core.StringRedisTemplace (e.g. save(); delete();) but only when the calls are made directly from within one of my corporation many packages com.mycompany.*, not when an instance of StringRedisTemplace is used by a third party library or spring/data/redis itself.

Is there a way to do that with AOP annotations like @Pointcut @Around, etc. My searches/attempts were unsuccessful.

So in one word => how to intercept/instrument all calls to all instances of a certain class as long as those instances were instantiated and used within my company packages.


Solution

  • Well, you are almost saying it by yourself:

    but only when the calls are made directly from within one of my corporation many packages com.mycompany.*

    The pointcut type you need is indeed named within. There is a related one named withincode in full AspectJ, but proxy-based Spring AOP only supports the former, not the latter. For the latter you would have to use full AspectJ via LTW from within Spring. Everything is explained in the Spring manual's AOP chapter.

    What you want to do is something like this:

    within(com.mycompany..*) && call(org.springframework.data.redis.core.StringRedisTemplate+.*(..))