spring @cacheable 注解使用spel表达式

这里主要讲一下复杂的spel表达式,简单的不写了

解析集合

集合需要先自定义一个方法,比如getAuthorsName,然后在注解里通过root.target.getAuthorsName把方法引用进去

public class BookService {
    public String getAuthorsName(List<Author> authors) {
        return authors.stream().map(Author::getName).collect(Collectors.joining("-"));
    }

@Cacheable(value="bookservice", key="'findBook:'+#root.target.getAuthorsName(#authors)")
    public Book findBook(List<Author> authors){
        // your logic here
    }
}

顺便附上root对象的说明

属性名称 描述 示例
methodName 当前方法名 #root.methodName
method 当前方法 #root.method.name
target 当前被调用的对象 #root.target
targetClass 当前被调用的对象的class #root.targetClass
args 当前方法参数组成的数组 #root.args[0]
caches 当前被调用的方法使用的Cache #root.caches[0].name

使用

@Component
public class CacheKeyGenerator 
  implements org.springframework.cache.interceptor.KeyGenerator {

    @Override
    public Object generate(final Object target, final Method method, 
      final Object... params) {

        final List<Object> key = new ArrayList<>();
        key.add(method.getDeclaringClass().getName());
        key.add(method.getName());

        for (final Object o : params) {
            key.add(o);
        }
        return key;
    }
}

@Cacheable(value="bookservice",keyGenerator="cacheKeyGenerator")
    public Book findBook(List<Author> authors){
        // your logic here
    }
}

posted @ 2024-09-19 16:21  leecoders  阅读(159)  评论(0)    收藏  举报