key属性是用来指定Spring缓存方法的返回结果时对应的key的。该属性支持SpringEL表达式。当我们没有指定该属性时,Spring将使用默认策略生成key。我们这里先来看看自定义策略,至于默认策略会在后文单独介绍。
自定义策略是指我们可以通过Spring的EL表达式来指定我们的key。这里的EL表达式可以使用方法参数及它们对应的属性。使用方法参数时我们可以直接使用“#参数名”或者“#p参数index”。下面是几个使用参数作为key的示例。
@Cacheable(value=”users”, key=”#id”)
public User find(Integer id) {
returnnull;
}
@Cacheable(value=”users”, key=”#p0″)
public User find(Integer id) {
returnnull;
}
@Cacheable(value=”users”, key=”#user.id”)
public User find(User user) {
returnnull;
}
@Cacheable(value=”users”, key=”#p0.id”)
public User find(User user) {
returnnull;
}
当我们要使用root对象的属性作为key时我们也可以将“#root”省略,因为Spring默认使用的就是root对象的属性。如:
@Cacheable(value={“users”, “xxx”}, key=”caches[1].name”)
public User find(User user) {
returnnull;
}
@Override @Cacheable(value={"TeacherAnalysis_public_chart"}, key="#root.target.getDictTableName() + '_' + #root.target.getFieldName()") public List
@Cacheable(value={"users"}, key="#user.id", condition="#user.id%2==0") public User find(User user) { System.out.println("find user by user " + user); return user; }
@CachePut("users")//每次都会执行方法,并将结果存入指定的缓存中 public User find(Integer id) { return null; }
@CacheEvict(value="users", allEntries=true) public void delete(Integer id) { System.out.println("delete user by id: " + id); }
@CacheEvict(value="users", beforeInvocation=true) public void delete(Integer id) { System.out.println("delete user by id: " + id); }
@Caching(cacheable = @Cacheable("users"), evict = { @CacheEvict("cache2"), @CacheEvict(value = "cache3", allEntries = true) }) public User find(Integer id) { return null; }
@Target({ElementType.TYPE, ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) @Cacheable(value="users") public @interface MyCacheable { }
那么在我们需要缓存的方法上使用@MyCacheable进行标注也可以达到同样的效果
@MyCacheable public User findById(Integer id) { System.out.println("find user by id: " + id); User user = new User(); user.setId(id); user.setName("Name" + id); return user; }
发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/220271.html原文链接:https://javaforall.net
