吾夜观天象,众星拱辰,星月交辉,大任将至,故寻|

leecoders

园龄:5个月粉丝:0关注:1

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
    }
}

本文作者:leecoders

本文链接:https://www.cnblogs.com/mi520/p/18420856

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

posted @   leecoders  阅读(86)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示
评论
收藏
关注
推荐
深色
回顶
收起