23

我想对@Cacheable没有参数的方法进行注释。在这种情况下,我使用 @Cacheable 如下

@Cacheable(value="usercache", key = "mykey")
public string sayHello(){
    return "test"
}

但是,当我调用此方法时,它不会被执行,并且会出现如下异常

org.springframework.expression.spel.SpelEvaluationException: EL1008E:(pos 0): 在“org.springframework.cache.interceptor.CacheExpressionRootObject”类型的对象上找不到属性或字段“mykey” - 也许不公开?

请建议。

4

4 回答 4

50

似乎 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"
}

您可以在此处找到可以在密钥中使用的 SPEL 表达式列表。

于 2015-10-28T06:29:14.050 回答
32

尝试在 . 周围添加单引号mykey。这是一个 SPEL 表达式,单引号又使它成为一个String

@Cacheable(value="usercache", key = "'mykey'")
于 2017-11-17T00:46:16.527 回答
0

在键中添加#

@Cacheable(value="usercache", key = "#mykey")
public string sayHello(){
    return "test"
}
于 2017-12-20T07:47:12.337 回答
0

您可以省略 key 参数。然后 Spring 会将键为SimpleKey.EMPTY的值放入缓存中:

@Cacheable("usercache")

或者(除了使用其他解决方案中概述的 SPEL 之外)您始终可以注入CacheManager并手动处理它。

于 2021-03-31T13:08:18.423 回答