0
0
SpringbootHow-ToBeginner · 4 min read

How to Use @CacheEvict in Spring Boot for Cache Management

Use @CacheEvict in Spring Boot to remove cache entries when data changes, ensuring cache consistency. Annotate methods with @CacheEvict(cacheNames = "cacheName", key = "#key") to evict specific cache entries or all entries with allEntries = true.
📐

Syntax

The @CacheEvict annotation is placed on methods to clear cache entries. Key parts include:

  • cacheNames: The name(s) of the cache(s) to evict from.
  • key: The key of the cache entry to remove, often using SpEL (Spring Expression Language).
  • allEntries: If true, removes all entries in the cache.
  • beforeInvocation: If true, eviction happens before the method runs (default is false).
java
@CacheEvict(cacheNames = "cacheName", key = "#key", allEntries = false, beforeInvocation = false)
public void methodName(Type key) {
    // method logic
}
💻

Example

This example shows a Spring Boot service that caches user data and evicts the cache when a user is updated.

java
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

@Service
public class UserService {

    @Cacheable(cacheNames = "users", key = "#userId")
    public String getUserById(String userId) {
        // Simulate fetching user data
        return "UserData for " + userId;
    }

    @CacheEvict(cacheNames = "users", key = "#userId")
    public void updateUser(String userId, String newData) {
        // Simulate updating user data
        System.out.println("Updated user " + userId + " with data: " + newData);
    }
}
Output
Updated user 123 with data: new info
⚠️

Common Pitfalls

  • Not specifying key correctly causes cache entries not to be evicted.
  • Forgetting allEntries = true when you want to clear the entire cache.
  • Eviction happening after method execution by default can cause stale data if the method fails.
  • Using @CacheEvict on private methods won't work because Spring proxies only public methods.
java
/* Wrong: No key specified, so cache entry may not be evicted as expected */
@CacheEvict(cacheNames = "users")
public void updateUserWrong(String userId) {
    // update logic
}

/* Right: Specify key to evict the correct cache entry */
@CacheEvict(cacheNames = "users", key = "#userId")
public void updateUserRight(String userId) {
    // update logic
}
📊

Quick Reference

Use this quick guide to remember @CacheEvict options:

OptionDescriptionDefault
cacheNamesName(s) of caches to evict fromRequired
keyCache key to evict, supports SpELAll entries if not set and allEntries=false
allEntriesEvict all entries in the cachefalse
beforeInvocationEvict before method runsfalse

Key Takeaways

Use @CacheEvict to remove stale cache entries after data changes.
Always specify cacheNames and key or use allEntries=true to clear caches correctly.
Eviction happens after method execution by default; use beforeInvocation=true to change this.
Do not use @CacheEvict on private methods as Spring proxies only public methods.
Combine @Cacheable and @CacheEvict to keep cache data fresh and consistent.