Sub topic 3
Enabling caching in a Spring Boot application
Prerequisites
This chapter assumes you can build a Spring Boot application with Maven or Gradle and that you understand beans and dependency injection. You should also know how to edit application.properties. The previous chapter explained the Cache and CacheManager interfaces. This chapter shows how to switch the abstraction on. It also covers what Boot sets up for you and the errors you are most likely to hit.
What "enabling" means
Spring does not cache anything until you ask it to. The caching annotations such as @Cacheable are only metadata. Something has to read them and act on them. That something is a set of infrastructure beans that @EnableCaching registers.
Enabling caching takes three steps:
- Add the cache starter dependency.
- Put
@EnableCachingon a configuration class. - Make sure a
CacheManagerexists, either by letting Boot create one or by defining your own.
Step 1: add the starter
The starter brings in the Spring cache support classes. Without it, @EnableCaching may fail to compile, or the cache classes may be missing at runtime.
For Maven:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>For Gradle:
implementation 'org.springframework.boot:spring-boot-starter-cache'This starter does not include a cache library. It gives you the abstraction and a simple in-memory fallback. Caffeine and Redis need their own dependencies, which later chapters cover.
Step 2: add @EnableCaching
Put the annotation on a class that Spring treats as configuration. The main application class qualifies, because @SpringBootApplication includes @Configuration.
@SpringBootApplication
@EnableCaching
public class ShopApplication {
public static void main(String[] args) {
SpringApplication.run(ShopApplication.class, args);
}
}In a larger project, a dedicated configuration class is often tidier. It also lets you switch caching off in tests by excluding that class.
What happens behind the scenes
@EnableCaching imports a configuration that registers three kinds of objects:
- A cache interceptor. It holds the logic that checks the cache, calls your method on a miss, and stores the result.
- A cache operation source. It reads the caching annotations on your beans.
- An advisor. It tells Spring which beans need a proxy, namely those with caching annotations.
After the context starts, Spring wraps each matching bean in a proxy. Other beans that inject ProductService receive the proxy, not the original object. A call goes through the proxy first. The proxy applies the cache logic and then, if needed, delegates to your real method.
This design explains most of the surprises later in the tutorial. Only calls that arrive through the proxy are cached. The chapter on proxy behavior returns to this point.
Step 3: the CacheManager
The interceptor needs a CacheManager to find caches by name. Boot's CacheAutoConfiguration creates one when three conditions hold:
- Caching is enabled, meaning a
CacheAspectSupportbean exists.@EnableCachingprovides it. - You have not defined your own
CacheManagerorCacheResolverbean. - No bean named
cacheResolverexists.
Boot then picks a provider by checking which libraries are on the classpath. The order is roughly: Couchbase, Hazelcast, Infinispan, JCache, Redis, Caffeine, and finally a simple fallback. You can see the full list in the Boot reference. If you set spring.cache.type, Boot uses that provider and fails at startup if it is unavailable.
With only the starter on the classpath, Boot uses ConcurrentMapCacheManager. This provider stores entries in a ConcurrentHashMap. It works for demos and tests, but it has no size limit and no expiration. Entries stay until you remove them, so it is unsuitable for production.
A minimal working example
Here is a service that uses the setup above. The method body stands in for a slow call.
@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 id returns the stored value, and the body does not run. Chapter four covers @Cacheable in detail. Here, the point is that the annotation takes effect only because you enabled caching.
Choosing the provider explicitly
Auto-detection is convenient, but it can surprise you. Adding a Redis dependency for another reason can silently switch your cache provider. Setting the type removes the guesswork:
spring.cache.type=caffeine
spring.cache.cache-names=products,productSearchThe cache-names property creates those caches at startup and, for most providers, restricts the cache manager to that list. A method that names an undeclared cache then fails with an IllegalArgumentException. This catches typos early. If you omit the property, ConcurrentMapCacheManager and Caffeine create caches on demand.
To turn caching off without removing annotations, set the type to none:
spring.cache.type=noneBoot then installs a NoOpCacheManager. Annotated methods run every time. This is useful for comparing behavior with and without a cache.
Proxy mode
@EnableCaching has attributes that control how the proxy is built:
| Attribute | Default | Meaning |
|---|---|---|
| `proxyTargetClass` | `false` | Use a class-based (CGLIB) proxy instead of an interface-based one. Boot overrides this and uses CGLIB by default. |
| `mode` | `PROXY` | `ASPECTJ` weaves the advice into the class at compile or load time. |
| `order` | lowest precedence | Position of the caching advice relative to other advisors, such as transactions. |
In a Boot application you rarely change these. The default CGLIB proxy works for classes that are not final and have non-final methods. A final class or method cannot be proxied that way, and the annotation is then ignored on that method. AspectJ mode removes the self-invocation limit but requires build-time or load-time weaving, which most projects avoid.
Common errors when enabling caching
The following table lists the problems you are most likely to meet at this stage.
| Symptom | Likely cause | Fix |
|---|---|---|
| Method runs every time, no errors | `@EnableCaching` is missing | Add it to a configuration class |
| Method runs every time, `@EnableCaching` present | The call is self-invocation, or the method is `private` or `final` | Call through another bean, and use a public, non-final method |
| Method runs every time, annotation on the interface only | A proxy type mismatch in older setups | Annotate the concrete class |
| `IllegalArgumentException: Cannot find cache named 'x'` | The cache is not listed in `spring.cache.cache-names` | Add the name, or remove the property |
| `NoSuchBeanDefinitionException` for `CacheManager` | Provider type is set but its library is missing | Add the dependency or fix `spring.cache.type` |
| Annotation has no effect on a bean created with `new` | The object never passed through Spring | Inject it as a bean |
Verifying that caching is on
A quick check uses the CacheManager bean directly. This runner prints the registered cache names after startup:
@Component
class CacheStartupReport implements ApplicationRunner {
private final CacheManager cacheManager;
CacheStartupReport(CacheManager cacheManager) {
this.cacheManager = cacheManager;
}
@Override
public void run(ApplicationArguments args) {
System.out.println("Cache manager: " + cacheManager.getClass().getSimpleName());
System.out.println("Caches: " + cacheManager.getCacheNames());
}
}With spring.cache.type=caffeine and the two cache names above, the output names CaffeineCacheManager and lists both caches. If the output names NoOpCacheManager, caching is disabled. If it names ConcurrentMapCacheManager when you expected Caffeine, the Caffeine library is probably missing from the classpath.
You can also start the application with --debug. Boot prints a conditions report that shows which cache configuration matched and why.
Summary of the setup
spring-boot-starter-cacheprovides the abstraction.@EnableCachingregisters the interceptor and creates proxies for annotated beans.- Boot creates a
CacheManagerfor the first provider it finds, unless you setspring.cache.typeor define your own. - The default fallback is an unbounded in-memory map, which is fine for learning and wrong for production.
Exercise
A service method is annotated with @Cacheable("products"). @EnableCaching is present and the starter is on the classpath. The application logs show the method body running on every call, and no exception is thrown. Name two causes you would check first.
Show answer
First, check whether the call is self-invocation, meaning another method in the same class calls it, so the call bypasses the proxy. Second, check that the method is public and not final, and that the bean is a Spring-managed bean rather than an object created with new. Also confirm that spring.cache.type is not set to none, which installs a no-op cache manager.
Exercise
You add spring-boot-starter-data-redis for another feature and do not set spring.cache.type. What can happen to your cache provider, and how do you prevent it?
Show answer
Boot auto-detects providers from the classpath. With Redis present and no other higher-priority provider, it can choose Redis as the cache provider, so cache entries move from local memory to Redis without any code change. Prevent this by setting spring.cache.type explicitly, for example spring.cache.type=caffeine.