Best Division

Spread Your Knowledge

  • All topics
  • About us
  • Contact us
  • Privacy policy
  • Terms of service
  • Copyright
  • Facebook
  • Twitter
  • Instagram
  • Youtube
  • LinkedIn
  • Pinterest
  • Github
  • Tumblr

© 2026 Best Division

How do you implement caching with Spring's @Cacheable annotation?

Java
Jayant Kumar
Jayant Kumar@jayantkumar314
PublishedJan 7, 2025
UpdatedNov 16, 2026
5 min read

Spring's @Cacheable annotation caches the return value of a method: before the method runs, Spring looks up a key in a named cache, returns the stored value on a hit, and otherwise runs the method and stores the result. You enable it with @EnableCaching and tune it with the attributes cacheNames, key, keyGenerator, condition, unless, sync and cacheManager.

The annotation works through a proxy around the bean, which explains most of its limits. Understanding the attributes and the proxy rules is what separates a cache that works from one that quietly does nothing.

Table of Contents

  • A minimal @Cacheable example
  • Choosing cache keys with key and keyGenerator
  • Controlling when to cache: condition and unless
  • Preventing duplicate loads with sync
  • Using several caches and cache managers
  • Proxy rules that make the cache silently fail
  • Frequently Asked Questions
    • What is the difference between value and cacheNames?
    • Does @Cacheable cache exceptions?
    • Can I cache a method with no arguments?
    • How do I clear a cache programmatically?
  • Summary

A minimal @Cacheable example

java

Enable it once in the application:

java

With a single parameter, Spring uses that argument as the key. With no parameters it uses a constant key; with several it combines them into a SimpleKey.

Choosing cache keys with key and keyGenerator

The key attribute takes a SpEL expression evaluated against the method arguments.

java

Parameter names are available as #name when the code is compiled with the -parameters flag, which Spring Boot's Maven and Gradle plugins enable by default. For repeated key logic, implement KeyGenerator and reference it with keyGenerator = "myGenerator". You cannot set both key and keyGenerator.

Controlling when to cache: condition and unless

AttributeEvaluatedCan use #resultEffect
conditionBefore the callNoIf false, the cache is skipped entirely (no lookup, no store)
unlessAfter the callYesIf true, the result is not stored
java

Use condition to restrict caching to some inputs, and unless to avoid storing empty or error-like results.

Preventing duplicate loads with sync

Under load, many threads can miss the same key together. Setting sync = true lets one thread compute while the others wait for its result.

java

Synchronization is per cache and per JVM, supports only one cache name and is not compatible with unless.

Using several caches and cache managers

java

With several names, Spring checks them in order and returns the first hit. Use cacheManager to route one method to a different provider when your application defines more than one manager bean. You can also place @CacheConfig(cacheNames = "items") on the class to avoid repeating the name.

Proxy rules that make the cache silently fail

  1. Self-invocation: this.priceFor(sku) inside the same class bypasses the proxy. Call it from another bean.
  2. Visibility: the default proxy mode intercepts public methods called from outside the bean.
  3. final classes and methods cannot be proxied by CGLIB.
  4. Mutable results: with in-memory caches the same object is returned each time, so callers can corrupt the cached value. Return records or immutable collections.
  5. Wrong key type: custom key classes need correct equals and hashCode.

Return types such as Optional<T> are unwrapped and re-wrapped, and CompletableFuture results are supported by providers that implement async caching, such as Caffeine.

Frequently Asked Questions

What is the difference between value and cacheNames?

They are aliases. cacheNames is the clearer name and is preferred in new code.

Does @Cacheable cache exceptions?

No. If the method throws, nothing is stored and the next call runs the method again.

Can I cache a method with no arguments?

Yes. Spring uses a default constant key, so the one value is cached until evicted or expired.

How do I clear a cache programmatically?

Inject CacheManager, call getCache("prices") and then clear(), or use @CacheEvict(allEntries = true).

Summary

@Cacheable stores a method's result under a key in a named cache and skips the method on later hits. Control keys with key, apply rules with condition and unless, avoid stampedes with sync, and always call cached methods through a Spring proxy so the cache is actually used.

Share