Scrivio Interview library
InternalsFoundations7 min read · updated 12 November 2026

Explain how Spring's cache abstraction intercepts a call to a method annotated with @Cacheable after you add @EnableCaching. Which beans are involved, how is the cache key computed by default, and how does Spring Boot decide which CacheManager to create?

@EnableCaching registers an advisor, a CacheInterceptor and a source that reads the caching annotations, and an auto-proxy creator wraps every bean that has those annotations in an AOP proxy. When a call reaches the proxy, the interceptor resolves the cache by name from the CacheManager, builds a key (by default the single argument, a SimpleKey of all arguments, or SimpleKey.EMPTY), returns the cached value on a hit and otherwise runs the method and stores the result. Spring Boot creates the CacheManager from what it finds on the classpath or from spring.cache.type, and falls back to a ConcurrentMapCacheManager when nothing else is present.

Why this question is asked

Caching looks like magic when we first meet it: we add one annotation and a slow method suddenly returns instantly. That magic hides real machinery, and when caching misbehaves in production (a cache that never hits, two methods that return each other's objects, a cache that grows without limit) we can only debug it if we know which beans are involved. Interviewers ask this question to see whether we understand that machinery rather than just the annotation. In this answer, we will recap what the cache abstraction is, look at the beans @EnableCaching registers, follow one call through the proxy, see how the default key is built, and finish with how Spring Boot chooses the CacheManager.

1A Quick Recap of the Cache Abstraction

Spring's cache abstraction is a thin layer between our code and a real cache. Our code talks to two small interfaces. A Cache is one named store of key-value pairs, with methods such as get, put and evict. A CacheManager is a registry that hands out a Cache when we ask for it by name, such as "products". The real storage lives in a provider: Caffeine for an in-process cache, Redis for a shared one, or a plain ConcurrentHashMap for the simplest case.

The annotations describe what we want. @Cacheable means: look in the cache first, and only run the method on a miss. @CachePut means: always run the method and store the result. @CacheEvict means: remove an entry. None of these annotations does anything by itself. They are only metadata until @EnableCaching (which Spring Boot users still add themselves) switches on the machinery that reads them.

2The Beans That @EnableCaching Registers

@EnableCaching imports a configuration that registers three cooperating beans. The first is a CacheOperationSource, specifically AnnotationCacheOperationSource, which reads @Cacheable, @CachePut, @CacheEvict and @Caching on a method and turns them into CacheOperation objects. The second is the CacheInterceptor, the piece of code that actually runs around our method. The third is an advisor, BeanFactoryCacheOperationSourceAdvisor, which pairs the interceptor with a rule saying which methods it applies to: those for which the operation source finds caching annotations.

On top of these, @EnableCaching makes sure an auto-proxy creator is registered. This is a bean post-processor, a hook that sees every bean after it is created. When it sees a bean with at least one method matched by the advisor, it replaces the bean with a proxy. A proxy is a wrapper object, generated at runtime, that looks like our class from the outside and passes calls through the interceptor first. Spring uses a JDK dynamic proxy when it proxies interfaces and a CGLIB subclass when it proxies the class itself. Spring Boot sets spring.aop.proxy-target-class=true by default, so in a Boot application we normally get CGLIB proxies.

Step throughWhat sits between the caller and our method
  1. Calleranother bean that injected PriceService
  2. AOP proxyJDK or CGLIB wrapper created by the auto-proxy creator
  3. CacheInterceptorasks the operation source what to do for this method
  4. CacheResolver and CacheManagerfind the Cache named in the annotation
  5. Cache providerCaffeine, Redis, JCache or a ConcurrentHashMap
  6. Target methodruns only on a miss or for @CachePut

6 layers, from the top down. Step through them one at a time.

Every layer above the target only exists because @EnableCaching registered it.

3Following One @Cacheable Call Through the Proxy

Let us follow a call to a cached method and see what happens at each step.

Java
@Service
class ProductService {
@Cacheable("products")
public Product find(long id) {
log.info("loading {}", id);
return repo.load(id);
}
}
productService.find(42); // loading 42 (miss: method runs, result stored)
productService.find(42); // no log line (hit: value returned from the cache)
productService.find(7); // loading 7 (different key, so another miss)
Step throughA miss followed by a hit
CallerProxy + CacheInterceptorCache "products"ProductService
find(42)
get(42)
null: a miss
find(42)
Product 42
put(42, Product 42)
Product 42
find(42) again
get(42)
Product 42: a hit
Product 42, method skipped

11 messages in order. Play them, or step through them one at a time.

When the first call arrives, the proxy hands it to CacheInterceptor. The interceptor asks the operation source which operations apply to find(); the answer is one cacheable operation on the cache named products. It then asks the CacheResolver, by default a SimpleCacheResolver backed by our CacheManager, for the Cache called products. Next it evaluates the key, and if a condition attribute is present it evaluates that too. It calls cache.get(key). On the first call there is nothing there, so it invokes the real method, then checks unless and puts the result into the cache.

On the second call the same steps run up to cache.get(key), which now returns a value. The interceptor returns it directly, and the real method never runs. Notice that all of this happens in the proxy. The CacheInterceptor itself has no idea about expiry or size limits; the abstraction leaves eviction policy and time to live to the provider. If we use a plain ConcurrentMapCacheManager, entries stay forever.

4How the Default Key Is Built

When we do not write a key attribute, the interceptor uses a KeyGenerator, and the default one is SimpleKeyGenerator. Its rules are short, and they explain several production bugs.

Java
// SimpleKeyGenerator, in effect
find() // key: SimpleKey.EMPTY
find(42L) // key: 42L (the argument itself)
find(42L, "EUR") // key: SimpleKey[42, EUR]
// Same value, different methods, same cache name:
byCode("USD") // key: "USD"
byIso("USD") // key: "USD" (collides with byCode in a shared cache)

With one argument, the argument itself becomes the key, so its equals() and hashCode() decide whether two calls hit the same entry. With several arguments, they are wrapped in a SimpleKey that compares all of them in order. With none, every call uses the single constant SimpleKey.EMPTY. Notice what is missing: the method name and the class are not part of the key. So two methods that share a cache name and are called with the same value will read each other's entries. We avoid that with separate cache names, an explicit SpEL key such as key = "#id", or a custom KeyGenerator.

5How Spring Boot Chooses the CacheManager

Spring Boot's CacheAutoConfiguration only acts when caching is enabled and we have not defined a CacheManager bean of our own. If we set spring.cache.type, Boot uses exactly that type. Otherwise it tries the supported providers in a fixed order and uses the first one it can configure: a generic setup built from Cache beans, then JCache (JSR-107), Hazelcast, Couchbase, Infinispan, Redis, Caffeine, Cache2k, and finally Simple. Simple means a ConcurrentMapCacheManager, an unbounded map with no expiry. Check your Boot version for the exact list, because providers have been added and removed over time; Ehcache 2, for example, is no longer supported directly and is reached through JCache.

So adding spring-boot-starter-data-redis to the classpath is enough to get a RedisCacheManager, and adding Caffeine is enough for a CaffeineCacheManager. Properties such as spring.cache.cache-names, spring.cache.redis.time-to-live and spring.cache.caffeine.spec then tune that manager, and CacheManagerCustomizer beans can adjust it further. Setting spring.cache.type=none gives a NoOpCacheManager, which is handy in tests when we want caching switched off.

6Follow-up questions

How would you switch to AspectJ mode and why?

We write @EnableCaching(mode = AdviceMode.ASPECTJ), add spring-aspects, and enable weaving, either at load time with @EnableLoadTimeWeaving and a weaving agent or at build time with the AspectJ compiler. Instead of wrapping the bean in a proxy, AspectJ weaves the caching logic into the class bytecode itself. The reason to do this is that the advice then applies to self-invocation and to methods a proxy cannot intercept. The cost is a more complex build or startup, so most teams only do it when restructuring the code is not an option.

What happens if you declare your own CacheManager bean?

Spring Boot's cache auto-configuration backs off completely, because it is conditional on no CacheManager being present. Our bean is used as is, and the spring.cache.* properties no longer configure anything unless our own code reads them. If we define more than one CacheManager, we must mark one @Primary or return it from CachingConfigurer.cacheManager(), otherwise startup fails because the interceptor cannot choose.

Is the key generator applied before or after the condition?

Both are evaluated before the method runs, and the condition decides whether the cache is used at all. If the condition is false, no lookup happens and nothing is stored, so the key is irrelevant for that call. The unless expression is the only one evaluated after the method, because it may refer to #result.

7Conclusion

In this answer, we saw that @EnableCaching registers an operation source that reads the annotations, a CacheInterceptor that runs the caching logic, and an advisor that ties them together, while an auto-proxy creator wraps annotated beans in JDK or CGLIB proxies. The interceptor resolves the cache by name, builds a key with SimpleKeyGenerator unless we give one, and either returns the cached value or runs the method and stores its result. Spring Boot picks the CacheManager from spring.cache.type or from the classpath and falls back to an unbounded ConcurrentMapCacheManager, and expiry and size limits always come from the provider, never from the abstraction.

What to say in the interviewAbout 80 seconds aloud

Open with

When I add @EnableCaching, Spring registers three things: an AnnotationCacheOperationSource that reads the caching annotations, a CacheInterceptor that holds the logic, and an advisor that applies the interceptor to methods with those annotations.

Then, if they want more

An auto-proxy creator then wraps each such bean in a proxy, CGLIB by default in Spring Boot. When a call comes through the proxy, the interceptor asks the CacheResolver for the named cache from the CacheManager, evaluates the condition, computes the key and does a get.

On a hit it returns the value and the method never runs; on a miss it calls the method, checks unless, and puts the result. The default SimpleKeyGenerator uses the argument itself when there is one, SimpleKey.EMPTY when there are none, and a SimpleKey of all arguments otherwise, and importantly it does not include the method name.

For the CacheManager, Spring Boot backs off if I define my own; otherwise it uses spring.cache.type if set, or detects providers on the classpath such as JCache, Redis or Caffeine, and falls back to a ConcurrentMapCacheManager, which is unbounded.

Two limits are worth saying: only calls through the proxy are cached, so self-invocation skips it, and TTL and eviction come from the provider, not from Spring.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Explain how Spring's cache abstraction intercepts a call to a method annotated with...": https://scrivio-interview-library.netlify.app/databases/caching/32ad5a0c66/