Sub topic 2
How Spring's cache abstraction works
This chapter explains what happens between a method call and the cache store. It assumes you know basic Spring Boot structure, beans and dependency injection, and how to add a dependency with Maven or Gradle. Later chapters cover the annotations and providers in detail. Here you build the working model they all rely on.
What the abstraction is
Spring's cache abstraction is a thin layer between your code and a caching library. It does not store anything itself. It defines two things:
- A small set of interfaces that describe a cache and a collection of caches.
- An interceptor that applies caching rules to method calls, based on annotations.
Your service code declares what to cache with annotations such as @Cacheable. The abstraction decides when to read, write, or remove entries. A provider such as Caffeine or Redis does the storing. You can change the provider by changing configuration, and the service code stays the same.
This also sets the limits. The abstraction offers the features that most providers share: get, put, evict, and clear. Provider-specific features, such as Caffeine's refresh-after-write or Redis data structures, are configured on the provider side and not through the annotations.
The two core interfaces
Cache
org.springframework.cache.Cache represents one named cache. These are its main methods:
| Method | Behavior |
|---|---|
| `get(Object key)` | Returns a `ValueWrapper`, or `null` if the key is absent |
| `get(Object key, Callable<T> loader)` | Returns the cached value, or calls the loader and stores its result |
| `put(Object key, Object value)` | Stores or replaces an entry |
| `putIfAbsent(Object key, Object value)` | Stores only if no entry exists |
| `evict(Object key)` | Removes one entry |
| `clear()` | Removes all entries in this cache |
get(key) returns a ValueWrapper instead of the raw value so that the abstraction can tell two cases apart. A null wrapper means no entry exists (a miss). A wrapper whose get() returns null means the entry exists and the cached value is null. Without this wrapper, a cached null could not be told apart from a miss.
CacheManager
org.springframework.cache.CacheManager is a registry of Cache instances by name. It has two methods: getCache(String name) and getCacheNames(). When your annotation says cacheNames = "products", Spring asks the CacheManager for the cache called products.
The following program uses both interfaces directly, with no annotations. It needs only spring-context on the classpath, which Spring Boot already provides.
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.cache.concurrent.ConcurrentMapCacheManager;
public class CacheApiDemo {
public static void main(String[] args) {
CacheManager manager = new ConcurrentMapCacheManager("products");
Cache cache = manager.getCache("products");
cache.put(1L, "Keyboard");
Cache.ValueWrapper hit = cache.get(1L);
System.out.println("hit: " + hit.get()); // hit: Keyboard
System.out.println("miss: " + cache.get(2L)); // miss: null
String loaded = cache.get(2L, () -> "Mouse"); // loader runs
System.out.println("loaded: " + loaded); // loaded: Mouse
System.out.println("now cached: " + cache.get(2L).get()); // now cached: Mouse
cache.evict(1L);
System.out.println("after evict: " + cache.get(1L)); // after evict: null
}
}ConcurrentMapCacheManager is the simplest built-in implementation. It keeps entries in ConcurrentHashMap instances and never expires them.
How annotations reach the cache
When you add @EnableCaching, Spring registers an advisor that matches beans with caching annotations. For each matching bean, Spring wraps the bean in a proxy. The proxy calls a CacheInterceptor before and after your method. Other beans receive the proxy when your class is injected, and so they never call your object directly.
For a @Cacheable method, the interceptor does these steps:
- It resolves which cache or caches to use, by calling a
CacheResolver. The default resolver looks up the names from the annotation in theCacheManager. - It builds a key, using the
keyexpression if you wrote one, and aKeyGeneratorif you did not. - It looks the key up in the cache.
- On a hit, it returns the cached value. Your method does not run.
- On a miss, it calls your method, stores the result, and returns it.
Two consequences follow from this design:
- Caching works only for calls that pass through the proxy. A method that calls another method on
thisskips the interceptor. The proxy chapter covers this trap. - The cache is checked before the method runs, so on a hit nothing inside the method executes. This includes logging, metrics, and other side effects.
The default key
If you do not give a key, the default SimpleKeyGenerator builds one from the arguments:
| Method arguments | Resulting key |
|---|---|
| None | `SimpleKey.EMPTY` |
| One argument | The argument itself |
| Several arguments | A `SimpleKey` wrapping all of them |
The key must have correct equals() and hashCode() implementations, because providers compare keys with them. Records, strings, and numbers work well. A plain class without these methods will never hit, since each instance is a different key. The next chapters show how to override the key with SpEL (Spring Expression Language).
Seeing it work
The service below counts how many times the real method runs. Calling it twice with the same id should run it once.
import java.util.concurrent.atomic.AtomicInteger;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
@Service
public class PriceService {
private final AtomicInteger calls = new AtomicInteger();
@Cacheable("prices")
public String priceOf(Long id) {
calls.incrementAndGet();
return "price-" + id;
}
public int callCount() {
return calls.get();
}
}A runner that checks the result and prints the active CacheManager type:
import org.springframework.boot.CommandLineRunner;
import org.springframework.cache.CacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class CacheDemoRunner {
@Bean
CommandLineRunner showCaching(PriceService service, CacheManager cacheManager) {
return args -> {
service.priceOf(7L);
service.priceOf(7L);
service.priceOf(8L);
System.out.println("real calls: " + service.callCount()); // 2
System.out.println("manager: " + cacheManager.getClass().getSimpleName());
System.out.println("caches: " + cacheManager.getCacheNames()); // [prices]
};
}
}The application class needs @EnableCaching, as shown in the next chapter. With only spring-boot-starter-cache on the classpath, the manager is ConcurrentMapCacheManager. The real call count is 2 because ids 7 and 8 each miss once, and the second call for 7 is a hit.
How Boot picks a CacheManager
Spring Boot auto-configures a CacheManager when caching is enabled and you have not defined your own bean of that type. It checks for providers in a fixed order. The ones relevant here are Redis, Caffeine, and the simple ConcurrentMapCacheManager as a fallback. The first provider whose library is on the classpath is used. You can force a choice with spring.cache.type, for example spring.cache.type=caffeine.
The fallback has two important properties. It never expires or limits entries, so memory grows with the number of distinct keys. It also creates caches dynamically, so any name in an annotation works. Once you list names with spring.cache.cache-names, most managers accept only those names, and an unknown name fails at startup or at the first call.
Extension points
Each step of the flow can be replaced, which is why the abstraction fits most providers:
CacheManager: define a bean to take full control of the cache setup.KeyGenerator: change the default key rule for every annotation.CacheResolver: choose caches at runtime, not from annotation names.CacheErrorHandler: decide what happens when the provider throws. By default the exception reaches the caller. A handler can log it and let the method run uncached, which keeps the application working when Redis is down.
Summary of the model
Cacheis one named store,CacheManageris the registry of them.- Annotations are applied by a proxy and a
CacheInterceptor, so only calls through the proxy are cached. - The key defaults to the arguments, and it needs value-based
equals()andhashCode(). - Boot picks a provider from the classpath, and you can override that with
spring.cache.typeor your own bean.
Exercise
A @Cacheable("prices") method priceOf(Long id) is called as priceOf(7L), priceOf(7L), and then priceOf(8L). Using the default key generator, how many times does the method body run, and what are the cache keys? What would change if the method took no arguments and was called three times?
Show answer
The body runs twice. The keys are 7L and 8L, because a single argument becomes the key itself. The second call for 7L is a hit and skips the body. With no arguments the key is SimpleKey.EMPTY for every call, so the body runs once and the next two calls are hits.
Exercise
You call cache.get(5L) on a Cache and receive a non-null ValueWrapper whose get() returns null. Is this a miss? Explain, and say why the API is designed this way.
Show answer
No, it is a hit on a cached null. A miss is signaled by cache.get(5L) itself returning null instead of a wrapper. The wrapper exists so the abstraction can distinguish "no entry" from "an entry whose value is null". Without it, a method that legitimately returns null would run again on every call.