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

BITSSANDESH picture BITSSANDESH · Aug 2, 2014 · Viewed 18.8k times · Source

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'

Answer

Manuel Jordan picture Manuel Jordan · Aug 2, 2014

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";
  • must be public
  • must be static and final

Then

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

Done