@Cacheable(value="usercache", key = "mykey") public string sayHello(){ return "test" }
無參方法,設置Cache的key值時,報錯
rg.springframework.expression.spel.SpelEvaluationException: EL1008E:(pos 0): Property or field ‘mykey’ cannot be found on object of type ‘org.springframework.cache.interceptor.CacheExpressionRootObject’ - maybe not public?
It seems that Spring doesn’t allow you to provide a static text for the cache key in the SPEL, and it doesn’t include as default the name of the method on the key, so, you could be in a situation when two methods using the same cacheName and without a key would potentially cache different results with the same key.
解決方案
@Cacheable(value="usercache", key = "#root.methodName") public string sayHello(){ return "test" }
或
public static final String MY_KEY = "mykey"; @Cacheable(value="usercache", key = "#root.target.MY_KEY") public string sayHello(){ return "test" }
參考:
無參數方法的@Cacheble註釋(@Cacheble annotation on no parameter method)
Spring Cache key生成策略, 不要想當然認爲是全類名+方法+參數