After defining a Spring Boot cache like so:
@Component
@CacheConfig(cacheNames = ["test"])
class TestCache {
@Cacheable(cacheNames = ["test"], key = "#testId")
fun find(testId: String): String { ... }
@CachePut(cacheNames = ["test"], key = "#testId")
fun put(testId: String, set: String): String { ... }
@CacheEvict(cacheNames = ["test"], key = "#testId")
fun evictByTestId(testId: String) { }
fun evictByFooId(fooId: String): Boolean {
/* some processing to convert fooId to testId */
val testId = fooId
evictByTestId(testId)
return true
}
}
when I try to evict an entry, it perfectly works using the method with the CacheEvict annotation:
e.g. cache.evictByTestId("test123")
but does not delete the cache entry (also no exception) when using the defined helper method, which processes some data and then calls the annotated eviction method:
e.g. cache.evictByFooId("test123")
I stepped through the code with the debugger, both testIds are definitely the same.
Is there some annotation missing on the evictByFooId method?
>Solution :
Spring annotations do not work when a method invokes another method in the same class. Spring uses AOP to implement many of their annotations and only external invocations cause annotation processing to occur. In your case your evictByFooId() method is calling evictByTestId(), a method in the same class with the @CacheEvict annotation. You will have to duplicate the @CacheEvict annotation on evictByFooId().