@Cacheable(value="users", key="#id")
key属性是用来指定Spring缓存方法的返回结果时对应的key的。该属性支持SpringEL表达式。当咱们没有指定该属性时,Spring将使用默认策略生成key。咱们这里先来看看自定义策略,至于默认策略会在后文单独介绍。
1. 自定义策略是指咱们能够经过Spring的EL表达式来指定咱们的key。这里的EL表达式能够使用方法参数及它们对应的属性。使用方法参数时咱们能够直接使用“#参数名”或者“#p参数index”。下面是几个使用参数做为key的示例。缓存
@Cacheable(value="users", key="#id") public User find(Integer id) { return null; } @Cacheable(value="users", key="#p0") public User find(Integer id) { return null; } @Cacheable(value="users", key="#user.id") public User find(User user) { return null; } @Cacheable(value="users", key="#p0.id") public User find(User user) { return null; }
2.除了上述使用方法参数做为key以外,Spring还为咱们提供了一个root对象能够用来生成key。经过该root对象咱们能够获取到如下信息。app
当咱们要使用root对象的属性做为key时咱们也能够将“#root”省略,由于Spring默认使用的就是root对象的属性:less
@Cacheable(value={"users", "xxx"}, key="caches[1].name") public User find(User user) { return null; }
若是要调用当前类里面的方法:code
@RequestMapping(value = "/dept/data") @ResponseBody @Cacheable(value = "echartDeptDataCache", key = "#root.target.getFormatKey()", unless = "#result == null") public Map<String, Object> deptChartData() { return null; }
/** * 生成key - echartDeptDataCache * * @param * @return */ public String getFormatKey() { return ShiroUtils.getLoginName() + "echartDeptDataCache"; }
划重点:要调用的方法要是public的。orm