背景
SpEL(Spring Expression Language),即Spring表达式语言,语言简洁,功能强大。
示例
private static final Cache<String, Expression> EXPRESSION_CACHE = CacheBuilder.newBuilder()
.maximumSize(8192)
.initialCapacity(512)
.expireAfterWrite(1L, TimeUnit.HOURS)
.build();
private static final ExpressionParser SPEL_PARSER = new SpelExpressionParser();
public static String parse(String expression, Map<String, Object> param) {
return parse(expression, String.class, param);
}
public static <T> T parse(String expression, Class<T> clazz, Map<String, Object> param) {
try {
Expression e = EXPRESSION_CACHE.get(expression, () -> SPEL_PARSER.parseExpression(expression));
EvaluationContext context = new StandardEvaluationContext();
for (Map.Entry<String, Object> entry : param.entrySet()) {
context.setVariable(entry.getKey(), entry.getValue());
}
return e.getValue(context, clazz);
} catch (ExecutionException e) {
throw new RuntimeException(e);
}
}
常见用法
- 字符常量
// error
String exp = "Const"
// OK
String exp = "'CityList'"
- 属性变量
String exp = "#cityCode"
- 字符拼接
字符串连接符:+
String exp = "'PRE'+#cityCode+'SUFF'"
String exp = "#cityCode + ':'+ #type"
- 嵌套对象属性
String exp = "#city.code"
String exp = "#city.code+'PRE'+#city.type+#code+'SUFF'"
注意
- 属性为 null会转化为 “null” 字符串
- 嵌套对象外层不能为null,否则抛 SpelEvaluationException 异常
- 嵌套对象外层非null,最后一层引用属性为null 则会转化为 "null"字符串
Reference
- https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#expressions
- https://www.jianshu.com/p/e0b50053b5d3
- https://www.jianshu.com/p/27fd3754bb9c