SpEL笔记

ExpressionParser parser = new SpelExpressionParser();
Expresion exp = parser.parseExpression("'Hello world'");
String message = (String)exp.getValue();

在表达式中,可以调用函数,可以访问属性(public属性或javaBean形式)

exp.getValue()
exp.getValue(Class<T>)
exp.getValue(EvaluationContext context)
exp.getValue(Object rootObject)
...
exp.setValue(EvaluationContext context, Object value)
exp.setValue(Object rootObject, Object value)

SpEL compilation:
三种模式 off, immediate, mixed
可以通过代码(SpelParserConfiguration)或系统属性(spring.expression.compiler.mode)设置


SpEL expressions can be used with XML or annotation-based configuration metadata for defining "BeanDefinition"s. In both cases the syntax to define the expression is of the form #{ <expression string> }
在expression string中可以直接使用其他bean

The @Value annotation can be placed on fields, methods and method/constructor parameters to specify a default value.


语法:
SpEL支持的字面量类型有strings, numeric, dates,  boolean, null
1. 通过“点”获取对象属性
Case insensitivity is allowed for the first letter of property names.
2. 通过“[下标]”获取数组或列表中的元素。
3. 通过“map['键']”获取map中的元素。
inline lists: parser.parseExpression("{1,2,3,4}")
inline maps: parser.parseExpression("{name: 'Nokola', dob: '10-July-1856'}")
array construction: parser.parseExpression("new int[4]"), or "new int[]{1,2,3}" or "new int[4][5]"

操作符:
关系表达式: In addition to standard relational operators SpEL supports the "instanceof" and regular expression based "matches" operator.
boolean falseValue = parser.parseExpression("'xyz' instanceof T(Integer)").getValue(Boolean.class);
boolean trueValue = parser.parseExpression("'5.00' matches '\^-?\\d+(\\.\\d{2})?$'").getValue(Boolean.class);
逻辑表达式: and or !
数学精达式: xxx

Assignment, Type, Constructors, Variables, Fucntions.
parser.parseExpression('Name').setValue(inventorContext, "Alexander Seovic");
// alternatively
String aleks = parser.parseExpression("Name = 'Alexander Seovic'").getValue(inventorContext, String.class);
parser.parseExpression("T(java.lang.Math).random()")
Inventor einstein = p.parseExpression("new org.spring.samples.spel.inventor.Inventor('Albert Einstein', 'German')").getValue(Inventor.class);
可以通过#variableName和#funcName访问变量和调用方法。
通过context.setVariable注册变量
通过context.registerFunction注册方法。

支持三元表达式,并且支持Elvis表达式 "name?:'Unknown'"
支持Safe Navigation operation "PlaceOfBirth?.City"
groovy也支持Elvis表达式和Safe Navigation operation

Collection Selection and Collection Projection
Selection: List<Inventor> list = (List<Inventor>)parser.parseExpression("Members.?[Nationality == 'Serbian']").getValue(societyContext);
Projection: List placesOfBirth = (List)parser.parseExpression("Members.![placeOfBirth.city]").getValue(societyContext);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值