Search code examples
javaspring-bootcachingspring-framework-beans

What's the difference between @CacheEvict(...) and @CacheEvict(value , allEntries )?


I noticed a few lines of @CacheEvict("Settings") in some source code and was curious if does the same thing as CacheEvict(value = "Settings" , allEntries = true )?


Solution

  • When @CacheEvict is specified without a key attribute, all method parameters are used to construct the key for the entry to be evicted, so

    @CacheEvict("Settings")
    public String doThing(String foo, Integer bar) {
        // ...
    }
    

    ... will evict the entry with the composite key {foo, bar}. The default key generator used to construct the composite key is SimpleKeyGenerator, which returns SimpleKey instances that hold references to the method parameters for comparison.

    If the method has no parameters, the default key is SimpleKey.EMPTY.

    The attribute allEntries can't be set to true if you do specify a key attribute; they're mutually exclusive. If it is set to true all entries in the cache will be removed every time the annotated method is called.

    So...

    @CacheEvict("Settings", allEntries = true)
    public String doThing(String foo, Integer bar) {
        // ...
    }
    

    ... will empty the Settings cache every time the method is called, regardless of the method parameters.