The @CacheEvict annotation tells Spring to remove entries from a cache when an annotated method runs. You use it on methods that change or delete data, so the next read through @Cacheable loads fresh data instead of a stale copy. Without eviction (or an update with @CachePut), a cache keeps serving old values until they expire.
Like all Spring cache annotations, @CacheEvict works through a proxy and only takes effect when caching is enabled. The sections below show the setup, every attribute, and the pitfalls that make eviction silently fail.
Add the cache starter and enable caching once on a configuration class:
With Spring Boot, add spring-boot-starter-cache; a simple in-memory ConcurrentMapCacheManager is configured automatically, and you can swap in Caffeine or Redis later without changing the annotations.
Now pair reads and writes:
After update(...) returns successfully, the entry for that product id is removed. The next find(id) call misses the cache, reads the database and stores the new value.
| Attribute | Purpose |
|---|---|
cacheNames / value | One or more cache names to evict from. |
key | SpEL expression for the entry to remove. Defaults to all method parameters. |
keyGenerator | Name of a custom KeyGenerator bean, used instead of key. |
cacheManager, cacheResolver | Select a specific manager or resolver. |
condition | SpEL expression; eviction happens only if it is true. |
allEntries | When true, clears the whole cache. key must not be set. |
beforeInvocation | When true, evicts before the method runs, so it happens even if the method throws. |
Use this sparingly: it is a blunt tool and clears entries other callers still use.
By default eviction happens after a successful call, so an exception leaves the cache untouched. Set beforeInvocation = true when the entry must be removed regardless of the outcome:
Use @Caching to combine annotations, or list several cache names:
This pattern keeps single-item caches and list caches consistent when one record changes.
@EnableCaching the annotation is ignored with no error.final classes. Proxies cannot intercept them reliably.@Cacheable. If find uses #id and eviction uses #product, nothing matches.@CacheEvict removes an entry, so the next read reloads it. @CachePut always runs the method and stores the result, so the cache is updated immediately.
Not by default. It evicts only after normal completion, unless beforeInvocation = true.
Yes, with allEntries = true. You can also call cacheManager.getCache("name").clear() programmatically.
You can, but it is confusing and rarely correct. Keep reads and writes on separate methods.
@CacheEvict keeps a Spring cache consistent with your data by removing entries when it changes. Enable caching, make the evict key match the cache key, use allEntries only when needed, choose beforeInvocation deliberately, and avoid self-invocation. For multi-instance deployments use a shared cache so one eviction reaches every node.