缓存注解上 key、condition、unless 等 SpEL 表达式的解析

SpEl 支持的计算变量:
1)#ai、#pi、#命名参数【i 表示参数下标,从 0 开始】
2)#result:CachePut 操作和后处理 CacheEvict 操作都可使用
3)#root:CacheExpressionRootObject 对象

计算上下文根对象

/**
* 缓存注解 SpEL 表达式计算上下文根对象
*/
class CacheExpressionRootObject {
/**
* 有效的缓存集合
*/
private final Collection<? extends Cache> caches;
/**
* 目标方法
*/
private final Method method;
/**
* 方法参数
*/
private final Object[] args;
/**
* 目标对象
*/
private final Object target;
/**
* 目标对象 Class 类型
*/
private final Class<?> targetClass;
}

缓存计算上下文【附加方法参数和返回结果作为计算变量】

/**
* 基于方法的表达式计算上下文
* @since 4.2
*/
public class MethodBasedEvaluationContext extends StandardEvaluationContext {
/**
* 目标方法
*/
private final Method method;
/**
* 参数数组
*/
private final Object[] arguments;
/**
* 参数名发现者
*/
private final ParameterNameDiscoverer parameterNameDiscoverer;
/**
* 参数变量是否已经加载
*/
private boolean argumentsLoaded = false; public MethodBasedEvaluationContext(Object rootObject, Method method, Object[] arguments,
ParameterNameDiscoverer parameterNameDiscoverer) {
super(rootObject);
this.method = method;
this.arguments = arguments;
this.parameterNameDiscoverer = parameterNameDiscoverer;
} @Override
@Nullable
public Object lookupVariable(String name) {
// 1)尝试从变量映射中读取指定名称的对象
Object variable = super.lookupVariable(name);
if (variable != null) {
return variable;
}
// 2)未读到 && 方法参数未加载
if (!this.argumentsLoaded) {
// 加载方法参数
lazyLoadArguments();
this.argumentsLoaded = true;
// 再次读取
variable = super.lookupVariable(name);
}
return variable;
} protected void lazyLoadArguments() {
// 无参数则直接退出
if (ObjectUtils.isEmpty(this.arguments)) {
return;
} // 读取目标方法的所有参数名称
String[] paramNames = this.parameterNameDiscoverer.getParameterNames(this.method);
// 计算形参个数,以解析到的参数名优先【可能存在可变参数】
int paramCount = (paramNames != null ? paramNames.length : this.method.getParameterCount());
// 实际传入的参数个数
int argsCount = this.arguments.length; for (int i = 0; i < paramCount; i++) {
Object value = null;
/**
* 实际传入的参数个数 > 形参个数
* && 将余下的所有入参都加入到数组中【目标方法最后一个参数是可变参数】
*/
if (argsCount > paramCount && i == paramCount - 1) {
value = Arrays.copyOfRange(this.arguments, i, argsCount);
}
// 读取实际参数
else if (argsCount > i) {
// Actual argument found - otherwise left as null
value = this.arguments[i];
}
/**
* 将 ai、pi、实际参数名称作为键,加入到计算变量映射中
* a0、p0 都表示第一个参数,依次类推
*/
setVariable("a" + i, value);
setVariable("p" + i, value);
if (paramNames != null) {
setVariable(paramNames[i], value);
}
}
}
} /**
* 缓存计算上下文,自动将方法参数添加为计算变量。
*/
class CacheEvaluationContext extends MethodBasedEvaluationContext {
/**
* 不可方法的变量集合
*/
private final Set<String> unavailableVariables = new HashSet<>(1);
CacheEvaluationContext(Object rootObject, Method method, Object[] arguments,
ParameterNameDiscoverer parameterNameDiscoverer) {
super(rootObject, method, arguments, parameterNameDiscoverer);
} /**
* 添加不可访问的变量名称
*/
public void addUnavailableVariable(String name) {
this.unavailableVariables.add(name);
} /**
* 读取变量的值
*/
@Override
@Nullable
public Object lookupVariable(String name) {
if (this.unavailableVariables.contains(name)) {
throw new VariableNotAvailableException(name);
}
return super.lookupVariable(name);
}
}

缓存注解上 SpEL 表达式计算器

/**
* 用于计算缓存注解上 SpEL 表达式值的工具类
*/
public abstract class CachedExpressionEvaluator {
/**
* 表达式解析器
*/
private final SpelExpressionParser parser;
/**
* 参数名称发现者
*/
private final ParameterNameDiscoverer parameterNameDiscoverer = new DefaultParameterNameDiscoverer(); protected CachedExpressionEvaluator(SpelExpressionParser parser) {
Assert.notNull(parser, "SpelExpressionParser must not be null");
this.parser = parser;
} protected CachedExpressionEvaluator() {
this(new SpelExpressionParser());
} protected SpelExpressionParser getParser() {
return parser;
} protected ParameterNameDiscoverer getParameterNameDiscoverer() {
return parameterNameDiscoverer;
} /**
* 将缓存注解上的 SpEL 表达式字符串解析为 Expression
*/
protected Expression getExpression(Map<ExpressionKey, Expression> cache,
AnnotatedElementKey elementKey, String expression) {
// 创建缓存键
final ExpressionKey expressionKey = createKey(elementKey, expression);
// 如果已存在则直接返回
Expression expr = cache.get(expressionKey);
if (expr == null) {
// 使用 SpelExpressionParser 解析表达式字符串
expr = getParser().parseExpression(expression);
// 写入缓存
cache.put(expressionKey, expr);
}
return expr;
} private ExpressionKey createKey(AnnotatedElementKey elementKey, String expression) {
return new ExpressionKey(elementKey, expression);
} protected static class ExpressionKey implements Comparable<ExpressionKey> {
/**
* 注解元素+目标类型
*/
private final AnnotatedElementKey element;
/**
* SpEL 表达式字符串
*/
private final String expression; protected ExpressionKey(AnnotatedElementKey element, String expression) {
Assert.notNull(element, "AnnotatedElementKey must not be null");
Assert.notNull(expression, "Expression must not be null");
this.element = element;
this.expression = expression;
} @Override
public boolean equals(Object other) {
if (this == other) {
return true;
}
if (!(other instanceof ExpressionKey)) {
return false;
}
final ExpressionKey otherKey = (ExpressionKey) other;
return element.equals(otherKey.element) &&
ObjectUtils.nullSafeEquals(expression, otherKey.expression);
} @Override
public int hashCode() {
return element.hashCode() * 29 + expression.hashCode();
} @Override
public String toString() {
return element + " with expression \"" + expression + "\"";
} @Override
public int compareTo(ExpressionKey other) {
int result = element.toString().compareTo(other.element.toString());
if (result == 0) {
result = expression.compareTo(other.expression);
}
return result;
}
}
} /**
* 处理缓存 SpEL 表达式解析的工具类
*/
class CacheOperationExpressionEvaluator extends CachedExpressionEvaluator {
/**
* 指示没有结果变量
*/
public static final Object NO_RESULT = new Object();
/**
* 结果变量不可使用
*/
public static final Object RESULT_UNAVAILABLE = new Object();
/**
* 计算上下文中,保存结果对象的变量名称
*/
public static final String RESULT_VARIABLE = "result";
/**
* key 表达式缓存
*/
private final Map<ExpressionKey, Expression> keyCache = new ConcurrentHashMap<>(64);
/**
* condition 条件表达式缓存
*/
private final Map<ExpressionKey, Expression> conditionCache = new ConcurrentHashMap<>(64);
/**
* unless 条件表达式缓存
*/
private final Map<ExpressionKey, Expression> unlessCache = new ConcurrentHashMap<>(64); public EvaluationContext createEvaluationContext(Collection<? extends Cache> caches,
Method method, Object[] args, Object target, Class<?> targetClass, Method targetMethod,
@Nullable Object result, @Nullable BeanFactory beanFactory) {
// 创建计算上下文的根对象
final CacheExpressionRootObject rootObject = new CacheExpressionRootObject(
caches, method, args, target, targetClass);
// 创建缓存计算上下文
final CacheEvaluationContext evaluationContext = new CacheEvaluationContext(
rootObject, targetMethod, args, getParameterNameDiscoverer());
// 1)方法返回值不可用
if (result == RESULT_UNAVAILABLE) {
evaluationContext.addUnavailableVariable(RESULT_VARIABLE);
}
// 2)方法返回值可用,则以 result 作为 key 将其加入到计算变量中
else if (result != NO_RESULT) {
evaluationContext.setVariable(RESULT_VARIABLE, result);
}
if (beanFactory != null) {
// 写入 BeanFactoryResolver
evaluationContext.setBeanResolver(new BeanFactoryResolver(beanFactory));
}
return evaluationContext;
} /**
* 计算键的值
*/
@Nullable
public Object key(String keyExpression, AnnotatedElementKey methodKey, EvaluationContext evalContext) {
return getExpression(keyCache, methodKey, keyExpression).getValue(evalContext);
} /**
* 计算 condition 值
*/
public boolean condition(String conditionExpression, AnnotatedElementKey methodKey, EvaluationContext evalContext) {
return Boolean.TRUE.equals(getExpression(conditionCache, methodKey, conditionExpression).getValue(
evalContext, Boolean.class));
} /**
* 计算 unless 值
*/
public boolean unless(String unlessExpression, AnnotatedElementKey methodKey, EvaluationContext evalContext) {
return Boolean.TRUE.equals(getExpression(unlessCache, methodKey, unlessExpression).getValue(
evalContext, Boolean.class));
} /**
* Clear all caches.
*/
void clear() {
keyCache.clear();
conditionCache.clear();
unlessCache.clear();
}
}

Spring 缓存注解 SpEL 表达式解析的更多相关文章

  1. Spring 缓存注解解析过程

    Spring 缓存注解解析过程 通过 SpringCacheAnnotationParser 的 parseCacheAnnotations 方法解析指定方法或类上的缓存注解, @Cacheable ...

  2. SPEL 表达式解析

    Spring Expression Language 解析器 SPEL解析过程 使用 ExpressionParser 基于 ParserContext 将字符串解析为 Expression, Exp ...

  3. Spring – 缓存注解

    Spring缓存抽象概述 Spring框架自身并没有实现缓存解决方案,但是从3.1开始定义了org.springframework.cache.Cache和org.springframework.ca ...

  4. Spring缓存注解@Cache使用

    参考资料 http://www.ibm.com/developerworks/cn/opensource/os-cn-spring-cache/ http://swiftlet.net/archive ...

  5. 【Spring】22、Spring缓存注解@Cache使用

    缓存注解有以下三个: @Cacheable      @CacheEvict     @CachePut @Cacheable(value=”accountCache”),这个注释的意思是,当调用这个 ...

  6. Spring缓存注解@CachePut , @CacheEvict,@CacheConfig使用

    Cacheable CachePut CacheEvict CacheConfig 开启缓存注解 @Cacheable @Cacheable是用来声明方法是可缓存的.将结果存储到缓存中以便后续使用相同 ...

  7. 详解Spring缓存注解@Cacheable,@CachePut , @CacheEvict使用

    https://blog.csdn.net/u012240455/article/details/80844361 注释介绍 @Cacheable @Cacheable 的作用 主要针对方法配置,能够 ...

  8. Spring缓存注解@Cacheable、@CacheEvict、@CachePut使用(转)

    原文地址:https://www.cnblogs.com/fashflying/p/6908028.html 从3.1开始,Spring引入了对Cache的支持.其使用方法和原理都类似于Spring对 ...

  9. Spring缓存注解@Cacheable

    @Cacheable @Cacheable 的作用 主要针对方法配置,能够根据方法的请求参数对其结果进行缓存 @Cacheable 作用和配置方法 参数 解释 example value 缓存的名称, ...

随机推荐

  1. xml的解析及案例的分析和分享

    HTML的文档如下: <!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset=& ...

  2. Scala Nothing 从官方DOC翻译

    Nothing is - together with scala.Null - at the bottom of Scala's type hierarchy. Scala中的Nothing和Null ...

  3. HTTP,FTP异常码大全【转载】

    HTTP 400 - 请求无效HTTP 401.1 - 未授权:登录失败HTTP 401.2 - 未授权:服务器配置问题导致登录失败HTTP 401.3 - ACL 禁止访问资源HTTP 401.4 ...

  4. JAVA中如何定义自定义注解

    了解注解 注解是Java1.5,JDK5.0引用的技术,与类,接口,枚举处于同一层次 .它可以声明在包.类.字段.方法.局部变量.方法参数等的前面,用来对这些元素进行说明,注释 . 在Java中,自带 ...

  5. 如何正确训练一个 SVM + HOG 行人检测器

    这几个月一直在忙着做大论文,一个基于 SVM 的新的目标检测算法.为了做性能对比,我必须训练一个经典的 Dalal05 提出的行人检测器,我原以为这个任务很简单,但是我错了. 为了训练出一个性能达标的 ...

  6. SpringBootMybatis 关于Mybatis-generator-gui的使用|数据库的编码注意点|各项复制模板

    mysql注意点: .有关编码 create table user( id int primary key auto_increment, `name` varchar(), `password` v ...

  7. mysql主从库配置读写分离以及备份

    1,什么是读写分离?其实就是将数据库分为了主从库,一个主库用于写数据,多个从库完成读数据的操作,主从库之间通过某种机制进行数据的同步,是一种常见的数据库架构.一个组从同步集群,通常被称为是一个“分组” ...

  8. C#基础知识之理解Cookie和Session机制

    会话(Session)跟踪是Web程序中常用的技术,用来跟踪用户的整个会话.常用的会话跟踪技术是Cookie与Session.Cookie通过在客户端记录信息确定用户身份,Session通过在服务器端 ...

  9. Redux 聊聊

    前言 Redux 是 JavaScript 状态容器,提供可预测化的状态管理. 首先明确一点的就是: Redux并不是React必须的,也没有任何依赖,你可以很自由的将他应用到各种前端框架.jQuer ...

  10. Vue结合webpack实现路由懒加载和分类打包

    https://blog.csdn.net/weixin_39205240/article/details/80742723