无参数方法的@Cacheble注释

@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生成策略, 不要想当然认为是全类名+方法+参数

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章