Sub topic 4
Caching method results with @Cacheable
This chapter assumes you can write a Spring Boot service, understand dependency injection, and have already added @EnableCaching and spring-boot-starter-cache to your project. Here you will learn how @Cacheable decides when to run your method and when to return a stored result.
The working model
@Cacheable marks a method whose result can be reused. Spring wraps the bean in a proxy. On each call, the proxy runs this sequence:
- Build a key from the method arguments.
- Look up the key in the named cache.
- On a hit, return the stored value. The method body does not run.
- On a miss, run the method, store the result under the key, and return it.
A first example
public record Product(Long id, String name, java.math.BigDecimal price) {}
@Service
public class ProductService {
private final Map<Long, Product> store = new ConcurrentHashMap<>();
@Cacheable(cacheNames = "products", key = "#id", unless = "#result == null")
public Product findById(Long id) {
// Imagine a slow database or remote call here.
return store.get(id);
}
}The first call to findById(1L) runs the method body. The second call with the same argument returns the stored Product without entering the method. Side effects in the body, such as logging or a counter, happen only on misses.
Attributes you will use most
| Attribute | Purpose |
|---|---|
| `cacheNames` (or `value`) | Names of the cache or caches to use. |
| `key` | A SpEL expression that builds the key. |
| `condition` | Decides before the call whether to use the cache. |
| `unless` | Decides after the call whether to skip storing the result. |
| `sync` | Makes concurrent misses for one key run the method only once. |
In unless, the variable #result holds the return value. In the example above, unless = "#result == null" keeps a missing product from being stored. Later chapters cover keys, conditions, and sync in detail.
Default key behavior
If you omit key, Spring uses a default key generator:
- No arguments: a fixed placeholder key.
- One argument: that argument itself.
- Several arguments: a key built from all of them.
The key relies on equals() and hashCode() of the arguments. A mutable argument whose hash code changes, or a class that does not override these methods, produces keys that never match.
Common errors
- Forgetting
@EnableCaching. The annotation compiles but does nothing, and the method runs every time. - Calling the method from the same class. Self-invocation bypasses the proxy, so no caching happens. A later chapter covers this.
- Caching a method with side effects. On a hit the body is skipped, so a save or a send never happens.
- Using a private or final method. The proxy cannot intercept it. Annotate public methods on a proxied bean.
- Caching mutable results. Callers who modify the returned object change the cached copy when the cache holds references, as local caches do.
Seeing it work
Add a log line or counter to the method body and call it twice with the same argument. If the line appears once, the cache is working. A test using CacheManager is covered in a later chapter.
Exercise
A method annotated with @Cacheable("products") is called twice with the argument 5. The method body increments a counter. What is the counter value after both calls, and what would make it 2?
Show answer
The counter is 1, because the second call is a hit and the proxy returns the stored value without running the body. It would be 2 if caching were not applied. Typical causes are a missing @EnableCaching, a call from within the same class that bypasses the proxy, or an entry that expired or was evicted between the calls.
Exercise
Why might findById(Long id) with unless = "#result == null" be preferable to caching every result?
Show answer
Without unless, a lookup for a product that does not exist stores null. If the product is created later through a path that does not update the cache, callers keep receiving the stale null. Skipping null results means each missing lookup is retried against the source.