0

I am trying to clear my cache after every 30 mins using a scheduler in SpringBoot.

@Scheduled(cron = "0 0/30 * * * ?)
@CacheEvict(value = { "cache1", "cache2" }, allEntries = true)
public void clear() {
      //clears caches  
}

This wasn't working initially. I referred to this post : @CacheEvict is not working in SpringBoot and started calling it from a different class and it worked.

My question is why does this happen? I couldn't find any answer over the internet.

  • Does this answer your question? [Spring cache @Cacheable method ignored when called from within the same class](https://stackoverflow.com/questions/12115996/spring-cache-cacheable-method-ignored-when-called-from-within-the-same-class) – Chin Huang Feb 09 '22 at 21:27

1 Answers1

1

This is not only for @cacheEvict but for all annotations on methods. Spring uses so called proxies to intercept the call and see which annotations are on a method to execute the logic for these annotations. But this can only be achieved when it's not an inner call.

See this https://spring.io/blog/2012/05/23/transactions-caching-and-aop-understanding-proxy-usage-in-spring

In proxy mode (which is the default), only external method calls coming in through the proxy are intercepted. This means that self-invocation, in effect, a method within the target object calling another method of the target object, will not lead to an actual transaction at runtime even if the invoked method is marked with @Transactional. Also, the proxy must be fully initialized to provide the expected behaviour so you should not rely on this feature in your initialization code, i.e. @PostConstruct.

MevlütÖzdemir
  • 3,180
  • 1
  • 23
  • 28