无参数方法的@Cacheble注释 [英] @Cacheble annotation on no parameter method

查看:1567
本文介绍了无参数方法的@Cacheble注释的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在没有参数的方法上具有@Cacheable批注.在这种情况下,我按如下方式使用@Cacheable

I want to have @Cacheable annotation on method with no parameter. In that case, I use @Cacheable as follows

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

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

However, when I call this method, it doesn't get executed and it get exception as below

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

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且没有密钥的两个方法可能会使用相同的密钥来缓存不同的结果.

It seems that Spring doesn't allow you to provide a static text for the cache key in the SPEL, and it doesn't include as default the name of the method on the key, so, you could be in a situation when two methods using the same cacheName and without a key would potentially cache different results with the same key.

最简单的解决方法是提供方法的名称作为键:

The easiest workaround is to provide the name of the method as the key:

@Cacheable(value="usercache", key = "#root.methodName")
public string sayHello(){
return "test"
}

这会将sayHello设置为键.

如果确实需要静态键,则应在类中定义一个静态变量,并使用#root.target:

If you really need a static key, you should define a static variable in the class, and use #root.target:

public static final String MY_KEY = "mykey";

@Cacheable(value="usercache", key = "#root.target.MY_KEY")
public string sayHello(){
return "test"
}

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

You can find here the list of SPEL expressions that you can use in your key.

这篇关于无参数方法的@Cacheble注释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆