If I am defining a ehcache for a method which doesn't have any parameter.
But in my use case I needs to access the my built cache through it's key.
So please provide me the better way of assigning key on it.
Follow is my code:
@Override
@Cacheable(value = "cacheName", key = "cacheKey")
public List<String> getCacheMethod() throws Exception{
P.S. I am getting the following error when I am trying to access this method from somewhere else.
org.springframework.expression.spel.SpelEvaluationException: EL1008E:(pos 0): Field or property 'cacheKey' cannot be found on object of type 'org.springframework.cache.interceptor.CacheExpressionRootObject'
Any data stored in a cache requires a key for its speedy retrieval. Spring, by default, creates caching keys using the annotated method's signature as demonstrated by the code above. You can override this using @Cacheable's second parameter: key. To define a custom key you use a SpEL expression.
@CacheableThis method-level annotation lets Spring Boot know that the return value of the annotated method can be cached. Each time a method marked with this @Cacheable is called, the caching behavior will be applied.
Annotation Type Cacheable. Annotation indicating that the result of invoking a method (or all methods in a class) can be cached. Each time an advised method is invoked, caching behavior will be applied, checking whether the method has been already invoked for the given arguments.
The cache key is the unique identifier for an object in the cache. Each object in the cache has a unique cache key. A cache hit occurs when a viewer request generates the same cache key as a prior request, and the object for that cache key is in the edge location's cache and valid.
The method has no parameter, therefore there is no a way to use a parameter/argument as a default key, and you can't use "static text" as a Key, you could do the following:
Declare the following
public static final String KEY = "cacheKey";
public
static
and final
Then
@Override
@Cacheable(value = "cacheName", key = "#root.target.KEY")
public List<String> getCacheMethod() throws Exception{
Done
In simple cases you can use an easier way: @Cacheable(key = "#root.methodName")
, and the key would be equal to annotated method's name
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