Video in progress

Middle 🌱 Spring

How does @Cacheable work, and when doesn't it behave as expected?

Before calling the method, the proxy builds a key from the arguments and checks the cache. On a hit the method isn't called and the value comes from the cache. On a miss the method runs and the result goes into the cache.

📖 Answer

@EnableCaching
@Configuration class CacheConfig { }

@Service
class CurrencyService {
    @Cacheable(cacheNames = "rates", key = "#code")
    public BigDecimal rate(String code) { return bankApi.fetch(code); } // slow external call

    @CacheEvict(cacheNames = "rates", key = "#code")
    public void refresh(String code) { }
}

If no cache provider is configured, Boot uses a plain ConcurrentHashMap — with no TTL and no size limit. In production use Caffeine (single instance) or Redis (multiple instances):

spring:
  cache:
    caffeine:
      spec: maximumSize=1000,expireAfterWrite=10m

When it doesn't work:

  • when called from the same class (self-invocation);
  • when the method is private;
  • when the argument object has broken equals/hashCode — every call becomes a new key;
  • a null result gets cached too — if you don't want that, unless = "#result == null".

Most important: cached values go stale. Agree with the business up front on how long it's acceptable to show old data.