我想在没有参数的方法上添加 @Cacheable
注释。在这种情况下,我按如下方式使用@Cacheable
@Cacheable(value="usercache", key = "mykey")
public string sayHello(){
return "test"
}
但是,当我调用此方法时,它没有被执行,并且出现如下异常
org.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?
请提出建议。
最佳答案
似乎 Spring 不允许您在 SPEL
中为缓存键提供静态文本,并且默认不包括键上的方法名称,所以,您可能会遇到两种方法使用相同的 cacheName
而没有键的情况,可能会使用相同的键缓存不同的结果。
最简单的解决方法是提供方法的名称作为键:
@Cacheable(value="usercache", key = "#root.methodName")
public string sayHello(){
return "test"
}
这会将 sayHello
设置为键。
如果你真的需要静态键,你应该在类中定义一个静态变量,并使用#root.target
:
public static final String MY_KEY = "mykey";
@Cacheable(value="usercache", key = "#root.target.MY_KEY")
public string sayHello(){
return "test"
}
您可以找到here您可以在 key 中使用的 SPEL 表达式列表。
关于spring - 无参数方法上的@Cacheble 注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33383366/