Skip to content

Spring Boot Cache Evict

DodaTech 1 min read

In this tutorial, you'll learn about Fix Spring Boot @CacheEvict Not Clearing. We cover key concepts, practical examples, and best practices.

The Problem

Cached values are not removed and stale data is returned after @CacheEvict.

Quick Fix

Use correct cache name

Wrong:

@CacheEvict("wrong-cache")
public void clear() { }

Output:

Wrong cache name

Right:

@CacheEvict("users")
public void clear() { }
// Must match @Cacheable("users")

Output:

Correct cache evicted

Evict all entries

Wrong:

@CacheEvict(value = "users", key = "#id")
public void deleteUser(Long id) { }

Output:

Only one entry evicted

Right:

@CacheEvict(value = "users", allEntries = true)
public void clearAll() { }

Output:

All user cache entries cleared

Use @Caching for multiple caches

Wrong:

@CacheEvict("users")
// Other caches not cleared

Output:

Multiple caches stale

Right:

@Caching(evict = {
    @CacheEvict("users"),
    @CacheEvict("userProfiles")
})
public void updateUser(User u) { }

Output:

Multiple caches cleared

Prevention

  • Match cache name between @Cacheable and @CacheEvict
  • Use allEntries = true to clear all entries
  • Use @Caching to evict multiple caches

Common Mistakes with boot cache evict

  1. Using head and tail instead of pattern matching, causing runtime errors on empty lists
  2. Forgetting that lazy evaluation defers computation until the value is forced, causing space leaks with unevaluated thunks
  3. Using return to exit a function early instead of wrapping a pure value in the monad

These mistakes appear frequently in real-world SPRING code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.

Practice Exercise

Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.

This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.

FAQ

### What happens if the cache name does not match?

CacheEvict silently does nothing if the cache name does not exist.

This quick fix is part of the DodaTech Spring & JVM ecosystem series. Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro