spring - 无参数方法上的@Cacheble 注释

标签 spring ehcache spelevaluationexception

我想在没有参数的方法上添加 @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/

相关文章:

java - JSON Web Token 如何验证用户的身份验证?

java - EhCache 使用过多的堆内存来存储值

java - Hibernate 配置相当于 ehcache.xml

spring - 是否可以填充 spring util :list via properties file?

java - Spring Security 生成空 CSRF token - 在空上找不到属性或字段 'parameterName'

Spring 表达式语言美元与哈希 ($ 与 #)

java - 关于spring容器热切单例设计模式

java - 我无法在 Spring-MVC 中访问 Robots.txt

java - hibernate - 进程范围的身份