5

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

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.

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

4

4 回答 4

22

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

声明以下内容

public static final String KEY = "cacheKey";
  • 一定是public
  • 必须是staticfinal

然后

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

完毕

于 2014-08-02T14:28:17.383 回答
6

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

于 2018-06-14T06:11:31.697 回答
2

请看一下这个春季文档

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

于 2014-08-02T12:56:31.733 回答
2

您可以使用键中的单引号将其再次变为 String 来解决此问题。

@Cacheable(value= CACHE_NAME.PRODUCT_CATLOG, key=" 'products' ")
    public List<Product> findAll() {
        return StreamSupport.stream(productRepository.findAll().spliterator(),false).collect(Collectors.toList());
    }
于 2020-06-13T06:50:47.020 回答