Spring Framework

Declarative Caching with Spring's Cache Abstraction

Intermediate7 min readUpdated

Spring's cache abstraction lets you memoise expensive method results with an annotation and plug in any cache store behind it. This guide explains what the annotations actually do at runtime, how keys are built, how to choose and configure a CacheManager, and why the hard part of caching is not storing values but invalidating them — with the patterns that keep cached data correct.

What you will learn

  • Enable caching and apply @Cacheable, @CachePut, @CacheEvict and @Caching with the right semantics
  • Control cache keys with SpEL and a custom KeyGenerator, and use condition and unless correctly
  • Configure a CacheManager backed by ConcurrentMap, Caffeine, JCache or Redis and set expiry where it belongs
  • Explain why caching runs through a proxy and what that means for self-invocation and private methods
  • Design an invalidation strategy that keeps cached data consistent with the source of truth

Caching is the fastest optimisation available to most applications and the source of some of their most confusing bugs. Spring's cache abstraction, in the spring-context module, gives you memoisation of method results through annotations and separates what to cache from where it is stored. The mechanics are simple; the discipline — deciding keys, expiry and invalidation — is where the value and the risk both live. This guide targets Spring Framework 6.x.

What the abstraction is

The abstraction consists of two interfaces. A Cache is a named key-value store with get, put, evict and clear. A CacheManager resolves caches by name and creates them on demand or from a configured list. Spring ships implementations for ConcurrentHashMap, Caffeine and JSR-107 JCache; Spring Data Redis adds RedisCacheManager; Hazelcast, Infinispan and others provide their own.

The annotations are applied by an AOP proxy, exactly like @Transactional. @EnableCaching registers the interceptor and a bean post-processor that proxies every bean carrying cache annotations. Each call to an annotated method on the proxy consults the cache before, after or instead of calling the real method.

@Configuration
@EnableCaching
public class CacheConfig {

    @Bean
    CacheManager cacheManager() {
        var manager = new CaffeineCacheManager("products", "priceLists");   // spring-context-support
        manager.setCaffeine(Caffeine.newBuilder()
                .maximumSize(10_000)
                .expireAfterWrite(Duration.ofMinutes(10))
                .recordStats());
        return manager;
    }
}

Naming the caches up front, as here, is better than letting the manager create them dynamically: a typo in a @Cacheable name then fails at startup instead of silently creating an unconfigured cache.

The annotations

@Service
public class ProductService {

    private final ProductRepository repository;

    public ProductService(ProductRepository repository) { this.repository = repository; }

    @Cacheable(cacheNames = "products", key = "#id", unless = "#result == null")
    public Product find(long id) {
        return repository.findById(id).orElse(null);        // runs only on a cache miss
    }

    @CachePut(cacheNames = "products", key = "#result.id")
    public Product update(long id, ProductUpdate change) {
        Product saved = repository.save(repository.require(id).apply(change));
        return saved;                                        // always runs; result replaces the cached entry
    }

    @CacheEvict(cacheNames = "products", key = "#id")
    public void delete(long id) {
        repository.deleteById(id);                           // runs, then the entry is removed
    }

    @Caching(evict = {
        @CacheEvict(cacheNames = "products", allEntries = true),
        @CacheEvict(cacheNames = "priceLists", allEntries = true)
    })
    public void importCatalogue(Path file) { … }
}
AnnotationBefore the callAfter the call
@CacheableLook up key; on hit, return cached value and skip the methodOn miss, store the result
@CachePutNothingAlways store the result under the key
@CacheEvictNothing (unless beforeInvocation = true)Remove the key, or everything with allEntries = true
@CachingGroups several of the above on one method—
@CacheConfigClass-level defaults for cacheNames, keyGenerator, cacheManager—

The distinction between @Cacheable and @CachePut matters more than it looks. @Cacheable is for reads: the method is a fallback when the cache is cold. @CachePut is for writes that also produce the new value: the method always executes and the cache is refreshed with what it returns. Putting both on one method is contradictory, and the reference documentation explicitly discourages it.

@CacheEvict(beforeInvocation = true) evicts even if the method throws; the default evicts only after a successful return, which is right for "delete then evict" and wrong for "evict then rebuild" workflows.

Keys

A cache entry is only as good as its key. By default SimpleKeyGenerator uses the single parameter as the key if there is exactly one, SimpleKey.EMPTY if there are none, and a SimpleKey wrapping all parameters otherwise. Every parameter therefore needs a correct equals and hashCode — a long or String is fine, a domain object that has not overridden equals is a key that never matches.

The key attribute takes a Spring Expression Language (SpEL) expression evaluated against the method:

ExpressionMeaning
#id or #p0The parameter named id (needs -parameters at compile time, which Spring Boot's build plugins enable) or the first parameter
#customer.id + ':' + #currencyA composite key from two parameters
#result.idThe return value — only valid in @CachePut and unless
#root.methodNameThe invoked method's name; also #root.target, #root.args
T(java.time.LocalDate).now()A static call — useful for daily buckets, dangerous elsewhere

For a key rule shared by many methods, implement KeyGenerator and reference it by bean name:

@Component("tenantKeyGenerator")
public class TenantKeyGenerator implements KeyGenerator {
    @Override
    public Object generate(Object target, Method method, Object... params) {
        return TenantContext.currentTenant() + ":" + method.getName() + ":" + Arrays.deepToString(params);
    }
}

@Cacheable(cacheNames = "reports", keyGenerator = "tenantKeyGenerator")
public Report monthly(YearMonth month) { … }

Forgetting the tenant, the locale or the currency in the key is how one user sees another's data. Anything that changes the method's result and is not a parameter must be part of the key or must not be cached.

Conditions

condition is evaluated before the call and can reference parameters; when false, the cache is neither read nor written. unless is evaluated after the call and can reference #result; when true, the result is not stored (but a cache hit is still returned). Use condition to skip caching for inputs that are unlikely to repeat — condition = "#query.length() > 3" — and unless to avoid caching nulls, errors or oversized payloads.

sync = true on @Cacheable makes concurrent callers with the same key wait for one computation instead of all hitting the backend at once — the cache stampede problem. It is supported by Caffeine and JCache-based managers; with it, unless and multiple cache names are not allowed on the same annotation.

Choosing a cache manager

ManagerWhere data livesExpiry / sizeUse when
ConcurrentMapCacheManagerJVM heapNoneTests, prototypes
CaffeineCacheManagerJVM heapSize, time, weight; near-optimal evictionSingle-instance or per-node caches; the default choice
JCacheCacheManagerProvider-dependent (Ehcache 3, Hazelcast, …)Provider policyStandards-based config or an existing JCache deployment
RedisCacheManager (Spring Data Redis)RedisPer-cache TTLMany instances must share one cache; survive restarts

A local cache is fast — nanoseconds — but each application instance holds its own copy, so an eviction on one node does not clear the others. A distributed cache is consistent across nodes but every read is a network round trip and every value must be serialisable. Many systems use both: a short-lived local layer in front of Redis. Spring's CompositeCacheManager can chain managers for lookups, but it does not implement a two-level write-through; that logic is yours or the provider's.

With Redis, decide the serialiser deliberately. JDK serialisation is the default and is brittle across deployments; a JSON serialiser with explicit type information is the usual choice. Whatever you pick, cached classes are now part of your compatibility surface — change a field and old entries fail to deserialise until they expire.

Invalidation strategy

The famous hard problem. Three approaches, in increasing order of cost and correctness:

  1. Time-based expiry only. Accept staleness up to the TTL. Correct for reference data, exchange rates, anything where a bounded lag is acceptable. Simplest and most robust because it needs no coordination.
  2. Explicit eviction on write. Every method that changes the data carries @CacheEvict or @CachePut for the affected keys. Precise, but every write path must be found, including bulk updates, batch jobs and direct SQL — and a cross-node cache is required for it to work with multiple instances.
  3. Event-driven invalidation. Writes publish a domain event; listeners evict on every node or in the shared cache. Handles multiple instances with local caches and decouples the writers from cache knowledge.

Combine 1 with 2 or 3: a TTL as a safety net catches the write path you missed. Evicting allEntries = true on any write is the blunt instrument that is often the right call for small caches with complex key relationships.

Caching and transactions interact in a way that is easy to get wrong. @EnableCaching and @EnableTransactionManagement both default their interceptor order to Ordered.LOWEST_PRECEDENCE, so when one method carries both @Transactional and @CacheEvict, which advice runs outermost is not guaranteed. If eviction happens before the commit, a concurrent reader can hit the database between the eviction and the commit, see the old row and repopulate the cache with stale data that then survives until the next eviction. Two fixes: give one of the @Enable… annotations an explicit order so eviction is the outer advice and runs after commit, or wrap the manager in TransactionAwareCacheManagerProxy (Spring Data Redis offers transactionAware() on its builder), which defers put and evict to the transaction's after-commit phase and discards them on rollback. The second option is the safer default whenever caches and transactions mix.

Common mistakes

Self-invocation. find(id) called from another method in ProductService bypasses the proxy and the cache. Split the cached method into another bean or inject the proxy.

Keys that ignore context. Tenant, locale, currency, user permissions — if it affects the result and is not in the key, users will see each other's data.

Caching mutable objects in a local cache. Every caller gets the same instance; one caller's modification is silently visible to all. Cache immutable values or defensive copies.

Unbounded ConcurrentMapCacheManager in production. No size limit, no expiry; it is a memory leak with a nice name.

@Cacheable on a method that has side effects. On a hit the method does not run, so the side effect does not happen. Cache pure lookups only.

Testing the cache with a plain new object. Nothing is cached. Use a Spring test context with @EnableCaching and assert on cacheManager.getCache("products").get(id).

Ignoring metrics. A cache with a 5 % hit rate is cost without benefit. Caffeine's recordStats() and Spring Boot's cache metrics show hit rates; watch them.

Key takeaways

  • The cache abstraction is Cache and CacheManager plus annotations applied by an AOP proxy after @EnableCaching.
  • @Cacheable skips the method on a hit, @CachePut always runs and refreshes, @CacheEvict removes; @Caching combines them.
  • Keys default to the parameters; make them explicit with SpEL or a KeyGenerator, and include every input that affects the result.
  • Expiry and size are configured on the provider, not in the annotations; Caffeine is the standard local choice, Redis the standard shared one.
  • Invalidation is the real design work: pair explicit eviction or events with a TTL safety net, and mind the ordering with transactions.
  • All AOP caveats apply — self-invocation, non-proxied objects and side-effecting methods defeat caching silently.

Sources and further reading

Frequently asked questions

Does Spring's cache abstraction support time-to-live?
Not directly. The abstraction defines put, get and evict; expiry, maximum size and eviction policy are properties of the underlying store. Configure them on the cache provider — Caffeine's expireAfterWrite, Redis cache configuration's entryTtl, a JCache expiry policy. ConcurrentMapCacheManager has no expiry at all, so entries live until evicted or the JVM stops.
Why is my @Cacheable method still executed every time?
The three usual causes: the call comes from another method in the same class (self-invocation bypasses the proxy), the method is not public on an interface-based proxy, or @EnableCaching is missing so no proxy was created. Less often, a condition or unless expression is filtering everything out, or the key differs on each call because an argument lacks a proper equals/hashCode.
Are null results cached?
By default yes, if the store supports null values — Spring wraps null so ConcurrentMap and Caffeine can hold it — which is useful for caching 'not found' but surprising when the value is null only temporarily. Add unless = "#result == null" to skip caching nulls. Redis serialises a null marker; JCache providers vary.
Should I cache at the repository or the service layer?
Cache the operation whose result is expensive and stable — usually a service method that composes several queries or a remote call, keyed by the business identifier. Caching individual repository calls tends to produce many small caches with unclear invalidation. Whichever layer you choose, put the @CacheEvict annotations next to the writes for the same data so both sides are visible together.