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);