0

@Cacheable @CacheEvict invalid

I has a service like this:

@service
pubic class TestService {

  @Cacheable(cacheNames ="user",key = "#userId")
  public User fetchUserById(Long userid) {
       return new User();
  }

  public User fetchCurrentUser() {
      return fetchUserById(124L);
  }
}

there is some problem:

@Cacheable is valid, when I invoke fetchUserById(Long userid).

but @Cacheable is invalid, when I invoke fetchCurrentUser().

P.PengFei
  • 11
  • 2

1 Answers1

0

You can find solution here : Spring cache @Cacheable method ignored when called from within the same class

This is because of the way proxies are created for handling caching, transaction related functionality in Spring. This is a very good reference of how Spring handles it - Transactions, Caching and AOP: understanding proxy usage in Spring

In short, a self call bypasses the dynamic proxy and any cross cutting concern like caching, transaction etc which is part of the dynamic proxies logic is also bypassed.

The fix is to use AspectJ compile time or load time weaving.