The @CacheEvict annotation

Spring's cache abstraction not only allows populating caches, but also allows removing the cached data from the cache. There is a stage in the application where you have to remove stale or unused data from the cache. In that case, you can use the @CacheEvict annotation, because it doesn't add anything to the cache unlike the @Cacheable annotation. The @CacheEvict annotation is used only to perform cache eviction. Let's see how this annotation makes the remove() method of AccountRepository as a cache eviction:

    @CacheEvict("accountCache ") 
    void remove(Long accountId); 

As you can see in the preceding code snippet, the value associated with the argument, accountId, is removed from the accountCache cache when the remove() method is invoked. The following are @Cacheable attributes:

  • value: This is an array of names of the cache to use
  • key: This is a SpEL expression to evaluate the cache key to be used
  • condition: This is a SpEL expression to evaluate true or false; if it is false, then the result of caching is not being applied to the method call
  • allEntries: This implies that if the value of this attribute is true, all entries will be removed from the caches
  • beforeInvocation: This means that if the value of this attribute is true, the entries are removed from the cache before the method is invoked, and if the value of this attribute is false (the default), the entries are removed after a successful method invocation
We can use the @CacheEvict annotation on any method, even a void one, because it only removes the value from the cache. But in case of the @Cacheable and @CachePut annotations, we have to use a non-void return value method, because these annotations require a result to be cached.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset