Use Spring Cache Annotations with Redis Backend
Apply Spring's @Cacheable, @CachePut, and @CacheEvict annotations with a Redis cache manager for declarative caching in Java applications.
Overview
Adding caching to a Spring service method takes one annotation: @Cacheable, @CachePut, @CacheEvict, or @Caching. Behind each annotation, an AOP proxy intercepts the call, checks the cache first, and either returns the stored value or runs the method and stores the result. Your business code never sees the plumbing. And because Redis is the backend here, every application instance reads and writes the same cache; a value stored by one node is a hit for all the others.
Below: the Redis CacheManager setup, how each annotation behaves (and the SpEL rules that bite people), conditional and multi-cache operations, and TTL configuration. For HTTP-layer caching, see HTTP Cache-Control Headers for APIs and Static Assets; for a local in-JVM alternative, see Configure Caffeine Cache in Java.
When to Use This
- Spring Boot services where the same expensive read happens over and over — database lookups, computed reports, remote calls
- Multi-instance deployments that need one shared cache instead of N local caches that drift apart (that’s the Redis part)
- Read-heavy methods whose results tolerate some staleness controlled by TTL
- Teams that want caching to live in annotations on the service layer, not threaded through business logic
If your service runs as a single instance and you only need a bounded local cache, Caffeine alone is simpler and faster — the annotations work with any CacheManager.
Prerequisites
- Java 17+
- Spring Boot 3+
- A running Redis instance (local
redis-serveror a container is enough) - Cached values must be serializable (the examples below use JSON via Jackson)
Solution
1. Add Dependencies
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
2. Configure the Redis Cache Manager
@Configuration
@EnableCaching
public class CacheConfig {
@Bean
public RedisCacheManager cacheManager(RedisConnectionFactory factory) {
RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(Duration.ofMinutes(10))
.disableCachingNullValues()
.serializeValuesWith(
RedisSerializationContext.SerializationPair.fromSerializer(
new GenericJackson2JsonRedisSerializer()));
// Per-cache TTL configuration
Map<String, RedisCacheConfiguration> cacheConfigs = new HashMap<>();
cacheConfigs.put("users", config.entryTtl(Duration.ofMinutes(5)));
cacheConfigs.put("products", config.entryTtl(Duration.ofMinutes(30)));
cacheConfigs.put("config", config.entryTtl(Duration.ofHours(24)));
return RedisCacheManager.builder(factory)
.cacheDefaults(config)
.withInitialCacheConfigurations(cacheConfigs)
.transactionAware()
.build();
}
}
3. @Cacheable — Skip the Method on a Cache Hit
@Service
public class UserService {
@Cacheable(value = "users", key = "#id")
public User getUserById(String id) {
// Only executed on cache miss
return userRepository.findById(id)
.orElseThrow(() -> new UserNotFoundException(id));
}
// Cache with a different parameter as key
@Cacheable(value = "users", key = "#email")
public User getUserByEmail(String email) {
return userRepository.findByEmail(email);
}
// condition sees the method arguments — evaluated BEFORE the call
@Cacheable(value = "users", key = "#id", condition = "#id != null")
public User getUserByIdConditional(String id) {
return userRepository.findById(id).orElseThrow();
}
// unless sees #result — evaluated AFTER the call, vetoes storing it
@Cacheable(value = "users", key = "#id", unless = "#result == null || !#result.active")
public User findUserById(String id) {
return userRepository.findById(id).orElse(null);
}
}
4. @CachePut — Always Execute, Then Update the Cache
@Service
public class UserService {
// Method always runs; the result replaces the cache entry
@CachePut(value = "users", key = "#user.id")
public User updateUser(User user) {
return userRepository.save(user);
}
// Update the cache right after creating — #result is available here
@CachePut(value = "users", key = "#result.id")
public User createUser(UserDto dto) {
User user = new User(dto.getEmail(), dto.getName());
return userRepository.save(user);
}
}
5. @CacheEvict — Remove Entries
@Service
public class UserService {
// Evict a single entry
@CacheEvict(value = "users", key = "#id")
public void deleteUser(String id) {
userRepository.deleteById(id);
}
// Evict every entry in the cache
@CacheEvict(value = "users", allEntries = true)
public void clearUserCache() {
// No-op — the annotation does the work
}
// Evict BEFORE the method runs — useful when the method may fail
@CacheEvict(value = "users", allEntries = true, beforeInvocation = true)
public void bulkUpdateUsers(List<User> users) {
userRepository.saveAll(users);
}
// Conditional eviction — condition sees the arguments, not the result
@CacheEvict(value = "users", key = "#user.id", condition = "#user.active == false")
public void deactivateUser(User user) {
user.setActive(false);
userRepository.save(user);
}
}
6. @Caching — Stack Several Operations on One Method
@Service
public class UserService {
@Caching(
evict = {
@CacheEvict(value = "users", key = "#id"),
@CacheEvict(value = "users", key = "#dto.email"),
@CacheEvict(value = "userList", allEntries = true),
}
)
public User updateUserAndEvictCaches(String id, UserDto dto) {
User user = userRepository.findById(id).orElseThrow();
user.setEmail(dto.getEmail());
user.setName(dto.getName());
return userRepository.save(user);
}
}
Note the SpEL keys reference actual parameter names (#id, #dto). A key like #user.email here would blow up at runtime — the method has no parameter called user.
7. Custom Key Generator
@Configuration
public class CacheConfig {
@Bean
public KeyGenerator customKeyGenerator() {
return (target, method, params) -> {
StringBuilder sb = new StringBuilder();
sb.append(target.getClass().getSimpleName()).append(":");
sb.append(method.getName()).append(":");
for (Object param : params) {
sb.append(param.hashCode()).append(":");
}
return sb.toString();
};
}
}
Usage:
@Cacheable(value = "users", keyGenerator = "customKeyGenerator")
public User getUser(String id, String tenantId) {
return userRepository.findByIdAndTenant(id, tenantId);
}
8. Class-Level Defaults with @CacheConfig
@Service
@CacheConfig(cacheNames = {"users", "userList"}) // Default cache names for the class
public class UserService {
@Cacheable(key = "#id")
public User getUserById(String id) {
return userRepository.findById(id).orElseThrow();
}
@CacheEvict(allEntries = true)
public void clearAll() {}
}
9. Verify the Cache Actually Works
Run the app, hit the endpoint twice, then look at Redis directly. The second call shouldn’t reach the database at all:
# Entries live under cacheName::resolvedKey
$ redis-cli KEYS 'users::*'
1) "users::42"
# The per-cache TTL from step 2 was applied automatically
$ redis-cli TTL 'users::42'
(integer) 298
A TTL of -1 means the key exists with no expiry — the entryTtl didn’t apply. That’s usually a sign the cache name in the annotation doesn’t match the key in withInitialCacheConfigurations.
How It Works
Spring wraps each @Cacheable-annotated bean in an AOP proxy. Every call goes through the proxy before it reaches your method:
On a miss the flow continues from the same decision:
SpEL timing: when each attribute sees what
Most @Cacheable bugs come from using a variable before it exists. The evaluation order matters:
| Attribute | Evaluated | Sees #result | Sees args (#id, #dto) | Used for |
|---|---|---|---|---|
key | Before the call | No | Yes | Which entry to read/write |
condition | Before the call | No | Yes | Skip caching entirely |
unless | After the call | Yes | Yes | Veto storing this result |
keyGenerator | Before the call | No | Yes (as params) | Custom key logic |
So condition = "#result.active == true" can’t work: there’s no result yet. Put result-based logic in unless instead, as shown in step 3. The same applies to @CacheEvict: condition sees only arguments, but because eviction runs after the method by default (beforeInvocation = false), #result is available there — one of the few asymmetries worth remembering.
What actually lands in Redis
RedisCacheManager writes entries under keys shaped like cacheName::resolvedKey — users::42 for the examples above. The value is the serialized object: with GenericJackson2JsonRedisSerializer, Jackson embeds the concrete class name in the JSON so it can deserialize back to User instead of a LinkedHashMap. That means:
- Cached classes need to stay deserializable — refactorings that move or rename them break existing entries (they’ll fail to deserialize, not silently return wrong data).
- The default TTL comes from
entryTtlon the cache config; per-cache overrides live inwithInitialCacheConfigurations. There’s no per-entry TTL in Spring’s annotation model — the closest thing is conditional eviction or a customRedisCacheWriter. disableCachingNullValues()stopsOptional.empty()-style misses from being stored asnullplaceholders, which would otherwise hide real misses and swallow exceptions.
It’s cache-aside, not read-through
The annotation model is cache-aside: on a miss, your method runs and the result gets stored. There’s no CacheLoader that fetches on your behalf, no refresh-ahead, and no stampede protection. If ten threads miss the same key at once, all ten run the method. For hot keys with expensive fills, add a synchronized block, a per-key lock, or move the hot path to Caffeine (which coalesces concurrent loads on a key through its LoadingCache). The Redis side has its own knobs — eviction policies, maxmemory, key expiry — covered in the Complete Guide to Redis Caching Strategies.
Variants
Caffeine + Redis Multi-Level Cache
@Configuration
public class CacheConfig {
@Bean
@Primary
public CompositeCacheManager cacheManager(
RedisCacheManager redisManager,
CaffeineCacheManager caffeineManager) {
CompositeCacheManager manager = new CompositeCacheManager(
caffeineManager, // L1 — checked first
redisManager // L2 — checked second
);
manager.setFallbackToNoOpCache(false);
return manager;
}
}
L1 serves most hits without a network round trip; L2 keeps instances consistent. Keep the Caffeine TTL short (seconds to a minute) so local copies don’t go stale for long.
Evict Another Cache Based on the Result
@CacheEvict runs after the method (with default beforeInvocation = false), so condition can inspect #result there — unlike @Cacheable. Evict a related cache only when the outcome warrants it:
@CachePut(value = "users", key = "#user.id")
@CacheEvict(value = "activeUsers", allEntries = true,
condition = "#result.active == false")
public User deactivateIfFraud(User user) {
user.setActive(fraudCheck(user));
return userRepository.save(user);
}
Here the activeUsers aggregate cache only resets when the saved user actually ended up inactive — not on every call.
Async Return Types (Spring 6.1+)
@Cacheable(value = "users", key = "#id")
public CompletableFuture<User> getUserAsync(String id) {
return CompletableFuture.supplyAsync(() ->
userRepository.findById(id).orElseThrow()
);
}
Since Spring Framework 6.1, the cache abstraction resolves async wrappers — CompletableFuture, Mono, Flux — and caches the resolved value, not the wrapper. On 6.0.x and earlier the wrapper itself was cached, which is almost never what you want; upgrade or use Mono.cache()/manual resolution.
Programmatic Cache Access
@Service
public class UserService {
@Autowired
private CacheManager cacheManager;
public void manualCacheOperation(String userId) {
Cache cache = cacheManager.getCache("users");
if (cache != null) {
// Manual put
cache.put(userId, new User(userId, "Alice"));
// Manual get
User cached = cache.get(userId, User.class);
// Manual evict
cache.evict(userId);
}
}
}
Useful for warming entries, surgical invalidation in batch jobs, or anything the annotations can’t express.
Best Practices
- Match the annotation to the operation:
@Cacheablereads,@CachePutwrites,@CacheEvictdeletes. Put@Cacheableon a mutating method and the mutation silently never runs on a hit. - Set per-cache TTLs: different data calls for different freshness.
withInitialCacheConfigurationsbeats one global TTL. - Use
unlessto veto storing results:unless = "#result == null"— or the!#result.activevariant above — keeps unwanted entries out. - Evict on writes: after an update or delete, evict the entry. Otherwise stale data is served until the TTL expires.
- Use
allEntries = truesparingly: clearing a whole cache causes a miss storm. Evict specific keys when you can. - Disable
nullcaching: a cachednullmasks real misses and swallows errors.disableCachingNullValues()stops it. - Handle cache outages explicitly: a dead Redis shouldn’t take down reads. Install a
CacheErrorHandlerthat logs and falls through to the method — see the FAQ for the bean.
Common Mistakes
- Using
@Cacheableon update methods:@Cacheableskips the method on a hit — the update never executes. Writes need@CachePut. - Missing
@EnableCaching: without it on a@Configurationclass, every cache annotation is a silent no-op. #resultinsidecondition: by the timeconditiongets evaluated the method hasn’t run, so there’s no result to look at. The expression either throws or never matches. Result checks belong inunless(or in@CacheEvict’scondition, which runs after the call by default).- Key names that don’t match parameters: SpEL resolves
#user.emailagainst the method’s parameter names. With(String id, UserDto dto)there’s nouser— use#dto.email— and with no names compiled in, Spring falls back to#a0/#p0style. Compile with-parameters(the Maven/Gradle defaults do this for Spring Boot) or annotate@Param-style explicitly. - Key collisions between methods: two methods caching into
userswith overlapping keys return each other’s values. Namespaces (users:by-id,users:by-email) or distinct key expressions fix it. - Caching mutable objects: mutate the object after storing and the cache holds the mutated reference (local caches) or the pre-mutation serialization (Redis). Prefer immutable DTOs.
- Not handling cache failures: when Redis is down, every cache operation throws. Install a
CacheErrorHandlerto log and continue — the FAQ shows one. - Expecting stampede protection: annotations don’t coalesce concurrent misses on the same key, so hot keys want a local cache in front or a lock in the app.
See Also
- Spring Framework caching reference — SpEL context, supported attributes, async support
- Spring Boot caching how-to — auto-configuration and supported providers
- Spring Data Redis reference —
RedisCacheManager, serializers, key spaces - Redis eviction and expiry docs — what happens server-side
- Companion code: runnable versions of every example in this recipe live in the stack-practices-resources repository under
resources/recipes/caching/java-spring-cache-annotations/.
Frequently Asked Questions
Spring Cache vs manual caching — which is better?
The annotations win for the common cache-aside pattern: one line per method, no boilerplate, backend-agnostic. Reach for CacheManager or RedisTemplate directly when you need per-entry TTL, conditional refresh, multi-level logic, or stampede control — the annotations can't express those.
Can I use @Cacheable with reactive Spring (WebFlux)?
Yes, on Spring Framework 6.1+. The cache abstraction resolves Mono/Flux/CompletableFuture return types and stores the resolved value. Before 6.1 the wrapper itself got cached — mostly useless — so on older versions use Mono.cache() or cache inside the pipeline instead.
How do I set different TTLs for different caches?
Through withInitialCacheConfigurations(Map<String, RedisCacheConfiguration>) on the RedisCacheManager builder — step 2 maps users→5min, products→30min, config→24h. Per-entry TTL isn't supported by the annotation model; you'd need a custom RedisCacheWriter or drop to RedisTemplate.
What happens when Redis is unavailable?
Every cache operation throws — reads included. Install a CacheErrorHandler that logs and lets the call fall through to the method:
@Bean
public CacheErrorHandler errorHandler() {
return new CacheErrorHandler() {
@Override public void handleCacheGetError(RuntimeException e, Cache cache, Object key) { log.warn("Cache get failed", e); }
@Override public void handleCachePutError(RuntimeException e, Cache cache, Object key, Object value) { log.warn("Cache put failed", e); }
@Override public void handleCacheEvictError(RuntimeException e, Cache cache, Object key) { log.warn("Cache evict failed", e); }
@Override public void handleCacheClearError(RuntimeException e, Cache cache) { log.warn("Cache clear failed", e); }
};
}
With this in place, a Redis outage degrades to uncached reads instead of errors — at the cost of extra load on whatever's behind the cache.
Why does my SpEL key fail with "no parameter named"?
Because SpEL keys resolve against parameter names, and the name in the expression must match a real parameter (#id, #dto) or the fallback index form (#a0, #p0). Also make sure you're compiling with -parameters — without it, Java strips parameter names and only the index forms work.
Does @Cacheable protect against cache stampedes?
No. A miss runs the method on every thread that arrives before the value is stored — nothing coalesces concurrent loads. If a hot key expires and 50 requests arrive together, all 50 hit the database. Mitigate with a short-TTL L1 (Caffeine) in front, a distributed lock, or Caffeine's LoadingCache semantics via a custom CacheManager.
Related Resources
Configure Caffeine Cache in Java with Eviction Policies
Set up Caffeine cache in a Java application with size-based, time-based, and weighted eviction policies for high-performance local caching.
RecipeImplement Redis Cache Invalidation in Node.js
Invalidate Redis cache entries in Node.js with TTL expiry, explicit deletion, pattern-based clearing, and pub/sub-based distributed invalidation.
RecipeHTTP Cache-Control Headers for APIs and Static Assets
Set Cache-Control, ETag, and Last-Modified headers to control browser and CDN caching for API responses and static assets
RecipeCache HTTP Responses with httpx and CacheControl in Python
Cache HTTP responses in Python using httpx with CacheControl for HTTP-compliant caching, ETag handling, and conditional requests.
GuideComplete Guide to Redis Caching Strategies
Choose and implement the right Redis caching pattern — cache-aside to refresh-ahead — with eviction, TTL, and production ops guidance.