44

I'm using Spring Cache abstraction and I have multiple caches defined. Sometimes, when data changes, I want to evict more than one caches. Is there away to evict multiple cache using Spring's @CacheEvict annotation?

2 Answers 2

92

You can do this:

@Caching(evict = {
    @CacheEvict("primary"),
    @CacheEvict(value = "secondary", key = "#p0")
})

Check out the Reference for details

2
  • How to do if 1 is @CachePut & another one is @CacheEvict? Commented May 23, 2019 at 13:32
  • 4
    The Kotlin version of this is: @Caching(evict = [ CacheEvict("primary"), CacheEvict(value = ["secondary"], key = "#p0") ]) Commented Sep 14, 2022 at 12:12
54

Keep it compact: You can evict multiple caches by enumerating them inside the @CacheEvict annotation:

@CacheEvict(value = { "cache1", "cache2" }, allEntries = true)
3
  • 1
    Well yeah, assuming you want the same additional arguments (allEntries = true) to apply to all caches you specify. In my experience that ain't often.
    – Madbreaks
    Commented Nov 17, 2017 at 21:20
  • How would you deal with keys with this syntax? Commented Sep 28, 2018 at 11:12
  • 3
    Can mention keys like this @CacheEvict(value = { "cache1", "cache2" }, key = "key")
    – YohanK
    Commented Oct 21, 2021 at 12:19