SpEL(Spring expression Language),即Spring表达式语言,语言简洁,功能强大。
示例private static final Cache常见用法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 param) { return parse(expression, String.class, param); } public static T parse(String expression, Class clazz, Map param) { try { expression e = expression_CACHE.get(expression, () -> SPEL_PARSER.parseexpression(expression)); evaluationContext context = new StandardevaluationContext(); for (Map.Entry 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"字符串
- 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



