javaspringehcachespelevaluationexception

What is the best way of defining key for @Cacheable annotation for Spring


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'


Solution

  • 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";
    

    Then

    @Override
    @Cacheable(value = "cacheName", key = "#root.target.KEY")
    public List<String> getCacheMethod() throws Exception{
    

    Done