I'm using spring
and @Cacheable
annotation to cache some database entries. I want to invalidate the full cache periodically.
Therefore: is it valid to just put these annotations on an interface method? Or do these annotations have to be placed on class methods (even if they have an empty method body)?
public interface MyRepository extends CrudRepository<MyEntity, Long> {
@Override
@Cacheable("cache")
Airline findOne(long id);
@CacheEvict(value = "cache", allEntries = true)
@Scheduled(cron = "0 0 1 * * *")
void removeAll();
}
The application starts up successfully if I have the @Cacheable
on the interface method and the @CacheEvict
in a service. It does not work if I use the code above. But maybe I'm also doing things wrong?
The idea of the @Cacheable annotation is that you use it to mark the method return values that will be stored in the cache. The @Cacheable annotation can be applied either at method or type level. When applied at method level, then the annotated method's return value is cached.
As the name implies, @Cacheable is used to demarcate methods that are cacheable - that is, methods for whom the result is stored into the cache so on subsequent invocations (with the same arguments), the value in the cache is returned without having to actually execute the method.
Spring Boot auto-configures the cache infrastructure as long as caching support is enabled via the @EnableCaching annotation.
@EnableCaching annotation is the annotation-driven cache management feature in the spring framework. This annotation has been added to the spring since the version 3.1. If you are using this annotation, then you are not required to write the XML bean definitions for cache manager. @EnableCaching in Spring Framework.
It would probably work, but I'd suggest to put these annotations on the implementation.
It's more of a theoretical question, but think of it this way: an interface is a common contract, but caching is an implementation detail.
Your interface could be implemented in a number of ways for example, one day you could have a HsqlDBRepository, for which caching doesn't make sense at all as it's already in memory.
On a side-note, I'd think carefully about why you need to 'evict all'... depending on how often it happens, it could render your caching useless - also it's often a sign of a deeper problem with the design. If you want to evict entities after some time, consider configuring timeToLive/timeToIdle - most cache backends support this nicely.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With