Search code examples
springspring-cache

Invocation of @CacheEvict annotation


I know that @CacheEvict performs a cleanup operation on the cached data in Spring.I just wanted understand ::

If I annotate a Method with @CacheEvict will it be invoked automatically just like @PreDestroy annotation of JSF.i.e at the time of bean object is being garbage collected?


Solution

  • @CacheEvict is not like @PreDestroy; it is not invoked automatically.

    As the documentation describes, @CacheEvict is evaluated anytime an @CacheEvict annotated bean method is invoked. You can conditionally control when the eviction actually occurs, along with whether the eviction occurs before the method executes or after (the default), using the @CacheEviction annotation, beforeInvocation attribute, along with controlling other settings.

    Spring's declarative configuration for @CacheEvict is also not tied to JVM garbage collection. Usually, you need to rely on the capabilities of the individual caching providers (e.g. ehcache, memcached), or more advanced providers such as (e.g. Apache Geode, Hazelcast or Redis) to configure, tune and control eviction triggers and actions at the JVM level.

    Each provider may have similar and also different capabilities in this regard.

    Hope this helps.