Sub topic 4
Caching method results with @Cacheable
@Cacheable is the annotation that does most of the work in Spring's cache abstraction. This chapter covers what it does at runtime, which attributes you will use most, and the behaviors that surprise people. It assumes you can build a Spring Boot service with Maven or Gradle and that you know how beans and dependency injection work. It also assumes caching is already enabled with @EnableCaching, as shown in the previous chapter.
What @Cacheable does
When you put @Cacheable on a method, Spring wraps the bean in a proxy. The proxy is a generated object that stands in front of your real bean. Each call to the method goes through four steps:
- The proxy builds a cache key from the method arguments.
- It looks that key up in the named cache.
- On a hit, it returns the stored value. Your method body does not run.
- On a miss, it runs your method, stores the return value under the key, and returns it.
The first call with a given key is slow because it runs the method. Later calls with the same key are fast because they read the stored value.
A runnable example
You need spring-boot-starter-cache on the classpath. If no other provider is present, Spring Boot falls back to a simple ConcurrentHashMap-based cache. That is enough for this chapter. Chapters on Caffeine and Redis cover real providers.
First, the application class and the value type:
package com.example.shop;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
@SpringBootApplication
@EnableCaching
public class ShopApplication {
public static void main(String[] args) {
SpringApplication.run(ShopApplication.class, args);
}
}package com.example.shop;
import java.math.BigDecimal;
public record Product(Long id, String name, BigDecimal price) {}Next, a service with a counter, so you can see how often the method body actually runs:
package com.example.shop;
import java.math.BigDecimal;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
@Service
public class ProductService {
private final Map<Long, Product> store = new ConcurrentHashMap<>();
private final AtomicInteger lookups = new AtomicInteger();
public ProductService() {
store.put(1L, new Product(1L, "Keyboard", new BigDecimal("49.90")));
}
@Cacheable(cacheNames = "products", key = "#id", unless = "#result == null")
public Product findById(Long id) {
lookups.incrementAndGet();
// Imagine a slow database or remote call here.
return store.get(id);
}
public int lookupCount() {
return lookups.get();
}
}Finally, a runner that calls the method three times:
package com.example.shop;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;
@Component
public class CacheDemo implements ApplicationRunner {
private final ProductService service;
public CacheDemo(ProductService service) {
this.service = service;
}
@Override
public void run(ApplicationArguments args) {
service.findById(1L);
service.findById(1L);
service.findById(1L);
System.out.println("Method body ran " + service.lookupCount() + " time(s)");
}
}The output is Method body ran 1 time(s). Three calls were made, and only the first reached the method body.
The attributes you will use most
| Attribute | Purpose |
|---|---|
| `cacheNames` (alias `value`) | Names the cache or caches to use. Required unless a class-level `@CacheConfig` supplies it. |
| `key` | A SpEL expression that builds the key. |
| `keyGenerator` | The bean name of a custom `KeyGenerator`. Use it instead of `key`, not together with it. |
| `condition` | A SpEL expression evaluated before the call. If it is false, the cache is skipped completely. |
| `unless` | A SpEL expression evaluated after the call. If it is true, the result is not stored. |
| `sync` | Makes concurrent misses for one key run the method only once. |
| `cacheManager` | Selects a specific `CacheManager` bean when the application has more than one. |
Later chapters cover key, condition, and sync in detail. For now, remember the difference between condition and unless. condition is checked before the method runs, so it can only see arguments. unless is checked afterward and can use #result.
The default key
If you omit key, Spring uses a default key generator with three rules:
- A method with no arguments uses a fixed empty key,
SimpleKey.EMPTY. - A method with one argument uses that argument as the key.
- A method with several arguments uses a
SimpleKeythat combines all of them.
Two consequences follow. The argument types need working equals and hashCode methods, because the cache compares keys with them. Also, two different methods that share a cache name share its key space. If findById(Long id) and findPriceById(Long id) both cache into products, a call to one with 1L can return the value stored by the other. Use separate cache names, or set explicit keys that include the method purpose.
What gets cached
Null results
Spring treats null as a legitimate return value. Providers that allow nulls, including the default map-based cache and Caffeine, store a placeholder for it. A missing product then stays "missing" until the entry expires or is evicted. That is sometimes useful, because it stops repeated lookups for ids that don't exist. It can also hide a record that is created a moment later. The example above uses unless = "#result == null" to avoid this. Pick one behavior on purpose.
Optional
If the method returns Optional<T>, Spring unwraps it. The cache holds the inner T, or a null placeholder for an empty Optional. Callers still receive an Optional.
Exceptions
If the method throws, nothing is stored and the exception reaches the caller. The next call tries again.
Mutable values
With an in-process cache, the cache holds a reference to the same object your method returned. If a caller changes that object, every later caller sees the change. Prefer immutable return types, such as records, or copy the value before modifying it. Redis stores serialized copies instead, so this problem does not appear there, but a different one does: the values must be serializable.
Void methods
A void method has no result to store, so @Cacheable is pointless there. Use it on methods that compute and return a value from their arguments.
Rules for cacheable methods
- The method should be deterministic for its key. If the result also depends on the current user, the clock, or other hidden state that is not in the key, the cache will serve wrong answers.
- The method should be safe to skip. A hit means the body does not run, so any side effect inside it, such as writing an audit row or sending a metric, only happens on a miss.
- The call must reach the proxy. It has to come from another bean, and the method must be public. Calls from inside the same class bypass caching. The self-invocation chapter covers this.
Common errors
| Symptom | Likely cause |
|---|---|
| The body runs on every call | `@EnableCaching` is missing, the call is a self-invocation, or the key differs each time (for example, an argument without `equals`). |
| `Cannot find cache named 'products'` | The provider restricts cache names, as when `spring.cache.cache-names` is set, and `products` is not listed. |
| `IllegalStateException` about no cache resolver | The annotation has no `cacheNames` and no `@CacheConfig` supplies one. |
| Stale or wrong values | Two methods share a cache name, or the data changed and nothing evicted the entry. |
| `NullPointerException` in a SpEL expression | `#result` was used in `condition`. The result does not exist yet at that point. |
Exercise
A service has @Cacheable("prices") BigDecimal priceOf(String sku). A caller invokes priceOf("A1") twice, then priceOf("a1"). With the default key generator, how many times does the method body run, and why?
Show answer
Twice. The first call misses and runs the body. The second call uses the same key "A1" and hits. The third call uses "a1", which is a different String under equals, so it misses and runs the body again. To treat both spellings as one key, use key = "#sku.toLowerCase()".
Exercise
You annotate a method @Cacheable(cacheNames = "users", condition = "#result != null"). What happens when the application starts handling requests, and what should you write instead?
Show answer
condition is evaluated before the method runs, so #result is not available and the expression fails or never behaves as intended. To avoid storing null results, use unless = "#result == null", which is evaluated after the method returns.