java 为 Spring 的 @Cacheable 注释定义键的最佳方法是什么

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25095160/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 07:19:49  来源:igfitidea点击:

What is the best way of defining key for @Cacheable annotation for Spring

javaspringehcachespelevaluationexception

提问by BITSSANDESH

If I am defining a ehcache for a method which doesn't have any parameter.

如果我为没有任何参数的方法定义 ehcache。

But in my use case I needs to access the my built cache through it's key.

但是在我的用例中,我需要通过它的键来访问我构建的缓存。

So please provide me the better way of assigning key on it.

所以请为我提供更好的分配密钥的方法。

Follow is my code:

以下是我的代码:

@Override
@Cacheable(value = "cacheName", key = "cacheKey")
public List<String> getCacheMethod() throws Exception{

P.S. I am getting the following error when I am trying to access this method from somewhere else.

PS 当我尝试从其他地方访问此方法时,出现以下错误。

org.springframework.expression.spel.SpelEvaluationException: EL1008E:(pos 0): Field or property 'cacheKey' cannot be found on object of type 'org.springframework.cache.interceptor.CacheExpressionRootObject'

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

回答by Manuel Jordan

The method has no parameter, therefore there is no a way to use a parameter/argument as a default key, and you can't use "static text" as a Key, you could do the following:

该方法没有参数,因此无法使用参数/参数作为默认键,并且您不能使用“静态文本”作为键,您可以执行以下操作:

Declare the following

声明以下内容

public static final String KEY = "cacheKey";
  • must be public
  • must be staticand final
  • 必须是 public
  • 必须是staticfinal

Then

然后

@Override
@Cacheable(value = "cacheName", key = "#root.target.KEY")
public List<String> getCacheMethod() throws Exception{

Done

完毕

回答by Rafik BELDI

Please take a look at this spring doc.

请看一下这个spring 文档

the key refers to the arguments of your method, you are having SpelEvaluationExceptionbecause cachekeyisn't among your method arguments.

键是指您的方法的参数,SpelEvaluationException因为cachekey不在您的方法参数中。

回答by Nikolai Shevchenko

In simple cases you can use an easier way: @Cacheable(key = "#root.methodName"), and the key would be equal to annotated method's name

在简单的情况下,您可以使用更简单的方法:@Cacheable(key = "#root.methodName"),并且键将等于带注释的方法的名称