I am trying to use @Cachable and @CacheEvict for managing redis cache via spring framework. Can one add @CacheEvict on private methods of the class?
I am trying to use @Cachable and @CacheEvict for managing redis cache via spring framework. Can one add @CacheEvict on private methods of the class?
@Cacheable is only evaluated when called between beans, even for public methods. Ie for this:
public class MyBean {
@Cacheable
public String getString(int i) {
return Integer.toString(i);
}
public void myOtherMethod() {
String myString = getString(2);
}
}
the caching will not be triggered.
Therefore, it does not make sense to declare a private method with @Cacheable.
Note that the same is true for Aspects (as suggested in the other solution); those are not triggered when calling intra-class methods either.
Method visibility and @Cacheable/@CachePut/@CacheEvict
When using proxies, you should apply the @Cache* annotations only to methods with public visibility. If you do annotate protected, private or package-visible methods with these annotations, no error is raised, but the annotated method does not exhibit the configured caching settings. Consider the use of AspectJ (see below) if you need to annotate non-public methods as it changes the bytecode itself.
Ref : https://docs.spring.io/spring/docs/3.2.0.RC1/reference/html/cache.html