概述
在Spring Cache注解属性中(比如key,condition和unless),Spring的缓存抽象使用了SpEl表达式,从而提供了属性值的动态生成及足够的灵活性。
下面的代码根据用户的userCode进行缓存,对于key属性,使用了表达式自定义键的生成。
public class UserService { private Map<Integer, User> users = new HashMap<Integer, User>(); { users.put(1, new User("1", "w1",37)); users.put(2, new User("2", "w2", 34)); } @Cacheable(value = "users", key = "#user.userCode" condition = "#user.age < 35") public User getUser(User user) { System.out.println("User with id " + user.getUserId() + " requested."); return users.get(Integer.valueOf(user.getUserId())); }
SpEl表达式
SpEL表达式可基于上下文并通过使用缓存抽象,提供与root独享相关联的缓存特定的内置参数。
名称 | 位置 | 描述 | 示例 |
methodName | root对象 | 当前被调用的方法名 | #root.methodname |
method | root对象 | 当前被调用的方法 | #root.method.name |
target | root对象 | 当前被调用的目标对象实例 | #root.target |
targetClass | root对象 | 当前被调用的目标对象的类 | #root.targetClass |
args | root对象 | 当前被调用的方法的参数列表 | #root.args[0] |
caches | root对象 | 当前方法调用使用的缓存列表 | #root.caches[0].name |
Argument Name | 执行上下文 | 当前被调用的方法的参数,如findArtisan(Artisan artisan),可以通过#artsian.id获得参数 | #artsian.id |
result | 执行上下文 | 方法执行后的返回值(仅当方法执行后的判断有效,如 unless cacheEvict的beforeInvocation=false) | #result |