Use when adding caching to Spring Boot 4 services, configuring cache providers and TTL policies, invalidating stale data, or diagnosing cache hit and miss behavior.
Use when adding caching to Spring Boot 4 services, configuring cache providers and TTL policies, invalidating stale data, or diagnosing cache hit and miss behavior.
allowed-tools
Read, Write, Bash
Spring Boot Cache Abstraction
Overview
6-step workflow for enabling cache abstraction, configuring providers (Caffeine,
Redis, Ehcache), annotating service methods, and validating behavior in
Spring Boot 3.5+ applications. Apply @Cacheable for reads, @CachePut for
writes, @CacheEvict for deletions. Configure TTL/eviction policies and expose
metrics via Actuator.
When to Use
Add @Cacheable, @CachePut, or @CacheEvict to service methods.
Configure Caffeine, Redis, or Ehcache with TTL and capacity policies.
Implement eviction strategies for stale data.
Diagnose cache misses or invalidation issues.
Expose hit/miss metrics via Actuator or Micrometer.
Instructions
Add dependencies — spring-boot-starter-cache plus a provider:
Caffeine: caffeine starter
Redis: spring-boot-starter-data-redis
Ehcache: ehcache starter
Enable caching — annotate a @Configuration class with @EnableCaching
and define a CacheManager bean.
Annotate methods — @Cacheable for reads, @CachePut for writes,
@CacheEvict for deletions.
Configure TTL/eviction — set spring.cache.caffeine.spec,
spring.cache.redis.time-to-live, or spring.cache.ehcache.config.
Shape keys — use SpEL in key attributes; guard with
condition/unless for selective caching.
Validate setup — run integration test to confirm cache hit on second
call; check GET /actuator/caches to verify cache manager registration;
query GET /actuator/metrics/cache.gets for hit/miss ratios.
Use JCache annotations (@CacheResult, @CacheRemove) for providers favoring
JSR-107 interoperability; avoid mixing with Spring annotations on the same method.
Cache reactive return types (Mono, Flux) or CompletableFuture values.
Apply HTTP CacheControl headers when exposing cached responses via REST.
Schedule periodic eviction with @Scheduled for time-bound caches.
Create a CacheManagementService for programmatic cacheManager.getCache(name).
Troubleshooting
If cache misses persist after adding @Cacheable:
Verify @EnableCaching is present on a @Configuration class.
Confirm the method is public and called from outside the class (Spring uses
proxies; self-invocation bypasses the cache).
Validate SpEL key expressions resolve correctly.
Confirm the cache manager bean is registered as cacheManager or explicitly
referenced via cacheManager = "myCacheManager".