SpEL小试牛刀

背景

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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值