2015-10-28 52 views
7

我想在没有参数的方法上有@Cacheable注解。在这种情况下,我使用@Cacheable如下@Cacheble无参数方法注释

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

然而,当我调用这个方法,它没有得到执行,并得到例外如下

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

请建议。

回答

16

看来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,你可以在你的钥匙使用SPEL表达式的列表。

+0

能否请您解释一下这条线 - 静态密钥(的myKey你的情况),也将没有任何意义,因为春天已经绑定缓存的具体方法。那么如果我没有明确地提及它,将会存储在缓存中的密钥是什么 – user3534483

+0

@ user3534483对不起,我错了Spring使用的默认密钥。我编辑了答案并添加了正确的信息。 – Ruben

+0

谢谢......它的工作 – user3534483

3

尝试在mykey附近添加单引号。这是一个SPEL表达式,单引号再次使它成为String

@Cacheable(value="usercache", key = "'mykey'") 
0

添加#在关键

@Cacheable(value="usercache", key = "#mykey") 
public string sayHello(){ 
    return "test" 
} 
相关问题