@CacheEvict helps remove old or unwanted data from the cache. This keeps your app's data fresh and correct.
@CacheEvict for invalidation in 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.
@CacheEvict(value = "books", key = "#id") public void removeBook(Long id) { ... }
@CacheEvict(value = "books", allEntries = true)
public void clearAllBooksCache() { ... }@CacheEvict(value = "books", key = "#book.id", beforeInvocation = true) public void deleteBook(Book book) { ... }
This service caches book names by id. When a book is updated, its cache entry is removed. You can also clear all cached books.
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"); } }
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.
@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.
Practice
@CacheEvict annotation in Spring Boot?Solution
Step 1: Understand cache behavior
Cache stores data to speed up repeated access, but stale data can cause issues.Step 2: Role of @CacheEvict
@CacheEvict is used to remove outdated cache entries after data changes to keep cache fresh.Final Answer:
To remove or invalidate cache entries after data changes -> Option AQuick Check:
@CacheEvict removes cache entries [OK]
- Confusing @CacheEvict with @CachePut or @Cacheable
- Thinking it adds cache entries instead of removing
- Assuming it configures cache storage
@CacheEvict to clear a cache named "users" after a method executes?Solution
Step 1: Identify correct attribute names
The correct attribute to specify cache names iscacheNamesorvalue. To clear all entries, useallEntries = true.Step 2: Match correct syntax
@CacheEvict(cacheNames = "users", allEntries = true) uses@CacheEvict(cacheNames = "users", allEntries = true), which is valid syntax.Final Answer:
@CacheEvict(cacheNames = "users", allEntries = true) -> Option AQuick Check:
cacheNames + allEntries = true [OK]
- Using wrong attribute names like cacheName or cache
- Confusing allEntries with clearAll or removeAll
- Missing quotes around cache name
@CacheEvict(cacheNames = "products", key = "#id")
public void deleteProduct(Long id) {
productRepository.deleteById(id);
}
What happens when deleteProduct(5L) is called?Solution
Step 1: Analyze @CacheEvict usage
The annotation specifiescacheNames = "products"andkey = "#id", so it targets the cache entry with the given id.Step 2: Effect of calling deleteProduct(5L)
Calling with id 5 removes the cache entry with key 5 from the 'products' cache.Final Answer:
The cache entry with key 5 in 'products' cache is removed -> Option BQuick Check:
@CacheEvict with key removes specific cache entry [OK]
- Assuming all cache entries are removed without allEntries=true
- Thinking it adds cache entries instead of removing
- Believing missing key causes runtime error
@CacheEvict(cacheNames = "orders", key = "#order.id")
public void cancelOrder(Order order) {
orderRepository.delete(order);
}
Why might the cache eviction not work as expected?Solution
Step 1: Understand SpEL key expression
The key expression#order.idaccesses the id property of the 'order' parameter. This requires 'order' to be non-null and have a valid id.Step 2: Identify why eviction might fail
If 'order' is null or its id is null, the cache key cannot be resolved, so eviction won't work as expected.Final Answer:
The key expression#order.idrequires the 'order' object to be non-null and have a valid id -> Option CQuick Check:
SpEL key needs valid object and property [OK]
- Assuming key expressions cannot use object properties
- Using wrong parameter names in key expression
- Believing @CacheEvict cannot handle complex keys
@CacheEvict usage correctly achieves this in the deleteUser method?
public void deleteUser(Long userId) {
userRepository.deleteById(userId);
// cache eviction here
}Solution
Step 1: Understand requirement
We want to clear all entries in "sessions" cache only, not affect "users" cache.Step 2: Analyze options
@CacheEvict(cacheNames = "sessions", allEntries = true) on deleteUser method clears all entries in "sessions" cache, matching requirement. @CacheEvict(cacheNames = {"users", "sessions"}, allEntries = true) on deleteUser method clears both caches, which is incorrect. @CacheEvict(cacheNames = "users", key = "#userId") on deleteUser method clears only one user key in "users" cache, not sessions. @CacheEvict(cacheNames = "sessions", key = "#userId") on deleteUser method clears one key in "sessions" cache, not all.Final Answer:
@CacheEvict(cacheNames = "sessions", allEntries = true) on deleteUser method -> Option DQuick Check:
allEntries=true clears entire cache [OK]
- Clearing wrong cache or multiple caches unintentionally
- Using key instead of allEntries to clear entire cache
- Assuming deleting user clears user cache automatically
Ready to prove it?
Pass the test and this pattern moves unknown
