What if your app could fix stale data problems all by itself, every time?
Why @CacheEvict for invalidation in Spring Boot? - Purpose & Use Cases
Imagine you have a website showing product details. When a product changes, you must update the displayed info everywhere manually.
Manually clearing or updating cached data is easy to forget, slow, and causes users to see old or wrong info.
@CacheEvict automatically removes outdated cache entries when data changes, keeping info fresh without extra work.
cache.remove('product_123'); // manually clear cache after update@CacheEvict(value = "products", key = "#id") public void updateProduct(Long id, Product p) { ... } // cache clears automatically
It enables automatic, reliable cache cleanup so your app always shows fresh data without extra code.
When an admin updates a product price, @CacheEvict clears the old cached price so customers see the new price immediately.
Manual cache clearing is error-prone and slow.
@CacheEvict automates cache invalidation on data changes.
This keeps your app data fresh and users happy.
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
