@CacheEvict helps remove old or unwanted data from the cache. This keeps your app's data fresh and correct.
0
0
@CacheEvict for invalidation in Spring Boot
Introduction
When you update or delete data and want to remove the old cached version.
When you want to clear all cached data after a big change.
When you want to remove cache for a specific key after a method runs.
When you want to avoid showing outdated information to users.
Syntax
Spring Boot
@CacheEvict(value = "cacheName", key = "#key", allEntries = false, beforeInvocation = false)
value is the name of the cache to clear.
key defines which cache entry to remove. Use SpEL (Spring Expression Language) to specify keys.
Examples
Removes the cache entry for the book with the given id.
Spring Boot
@CacheEvict(value = "books", key = "#id") public void removeBook(Long id) { ... }
Clears all entries in the 'books' cache.
Spring Boot
@CacheEvict(value = "books", allEntries = true)
public void clearAllBooksCache() { ... }Evicts cache before the method runs, useful if method might throw exceptions.
Spring Boot
@CacheEvict(value = "books", key = "#book.id", beforeInvocation = true) public void deleteBook(Book book) { ... }
Sample Program
This service caches book names by id. When a book is updated, its cache entry is removed. You can also clear all cached books.
Spring Boot
import org.springframework.cache.annotation.CacheEvict; import org.springframework.cache.annotation.Cacheable; import org.springframework.stereotype.Service; @Service public class BookService { @Cacheable(value = "books", key = "#id") public String getBook(Long id) { // Simulate fetching book from database return "Book" + id; } @CacheEvict(value = "books", key = "#id") public void updateBook(Long id, String newName) { // Simulate updating book in database System.out.println("Updated book " + id + " to " + newName); } @CacheEvict(value = "books", allEntries = true) public void clearCache() { System.out.println("Cleared all books cache"); } }
OutputSuccess
Important Notes
Use allEntries=true carefully; it clears the whole cache which might affect performance.
beforeInvocation=true evicts cache before method runs, useful if method might fail.
Cache keys use Spring Expression Language (SpEL) to pick which cache entry to remove.
Summary
@CacheEvict removes cache entries to keep data fresh.
Use it after data changes to avoid stale cache.
You can remove specific keys or clear entire caches.