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@CacheEvictto 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-cacheplus a provider:
- Caffeine:
caffeinestarter - Redis:
spring-boot-starter-data-redis - Ehcache:
ehcachestarter
- Enable caching — annotate a
@Configurationclass with@EnableCaching
and define a CacheManager bean.
- Annotate methods —
@Cacheablefor reads,@CachePutfor 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
keyattributes; 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.
Examples
Example 1: Basic `@Cacheable` Usage
@Service
@CacheConfig(cacheNames = "users")
class UserService {
@Cacheable(key = "#id", unless = "#result == null")
User findUser(Long id) { ... }
}
First call → cache miss, repository invoked
Second call → cache hit, repository skipped
Example 2: Conditional Caching with SpEL
@Cacheable(value = "products", key = "#id", condition = "#price > 100")
public Product getProduct(Long id, BigDecimal price) { ... }
// Only expensive products are cached
Example 3: Cache Eviction
@CacheEvict(value = "users", key = "#id")
public void deleteUser(Long id) { ... }
For progressive scenarios (basic product cache, multilevel eviction, Redis