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

BIT*_*ESH 4 java spring ehcache spelevaluationexception

如果我为没有任何参数的方法定义了一个ehcache.

但在我的用例中,我需要通过它的密钥访问我构建的缓存.

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

关注是我的代码:

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

PS当我尝试从其他地方访问此方法时,我收到以下错误.

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

Man*_*dan 14

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

声明以下内容

public static final String KEY = "cacheKey";
Run Code Online (Sandbox Code Playgroud)
  • 一定是 public
  • 必须staticfinal

然后

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

完成


Nik*_*nko 5

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