0

So, I am trying to add a logging aspect to my spring caching, that will execute(at least I was hoping) every time before the @Cacheable annotation.

I have my DAO object where certain methods have the @Cacheable annotation:

@Cacheable(value = "BalanceGroupCahce", key = "#balanceGroupId")
 public BalanceGroup fetchBalanceGroup(Integer userId, Integer balanceGroupId) {
     //code to fetch balanceGroup from database;
     return balanceGroup;
  }

And I also have an aspect that defines a @Pointcut as the following:

@Pointcut(value="@annotation(org.springframework.cache.annotation.Cacheable)")
public void cacheablePointcut(){}

And a @Before advice that will get the the annotation as a parameter and will attach the logger to the appropriate cache:

@Before(value="cacheablePointcut() && @annotation(annotation)")
 public void addLoggerForCacheable(JoinPoint joinPoint, Cacheable annotation){
     //code to add the logger
 }

So what is happening is that everything works fine as long the requested resource was NOT found in the cache. When the resource was found in t he cache neither the method nor the @Cacheable annotation is executed. Which means that also my advice is not triggered. I knew that the method is not executed if spring finds the resource in the cache, but I thought that the @Cacheable annotation will still execute thus my pointcut too.

But apparently neither the @Cacheable annotation is executed, which means someone else is checking whether the resource is in the cache or not.

So the question is how could I rewrite my @Pointcut in order to be executed every time the cache is tested/updated/evicted? Also I am very curious who is testing if the resource is in the cache or not?

  • Unrelated but you have a typo in your pointcut. Would be nice to paste exactly what you're running (or better yet, share a sample we can run). The method is not executed at all, that's why your pointcut is not invoked. – Stephane Nicoll Nov 24 '16 at 07:43
  • Thank you for pointing it out. I edited it and now it looks exactly how I use it. As I said it does execute in case the object was not found in the cache. I think the implementation within the functions is not relevant, that it is why I skipped it, the rest is exactly the same. And anyway when I tested it I just had a System.out.println() in my "@Before". Let me know if you have any leads. Thank you – user2870461 Nov 24 '16 at 12:03
  • Did you check the java generated code, Did you try to use http://stackoverflow.com/questions/9051728/ordering-aspects-with-spring-aop-mvc, to try to put your aspectec around the cacheable object? – Javier Toja Nov 24 '16 at 12:31
  • 1
    Well, when the value is cached it should not be fetched from the database. Isn't this what `@Cacheable` is all about? To avoid calling expensive methods and return values from the cache instead? So if the method is not invoked, why should its `@Before` advice run at all? – kriegaex Nov 26 '16 at 23:16

0 Answers0