文本表达式支持字符串、 日期 、 数字(正数 、 实数及十六进制数) 、 布尔类型及 null。其中的字符表达式可以使用单引号来表示,形如:'Deniro'
。若是表达式中包含单引号或者双引号字符,那么可使用转义字符 /
。java
ExpressionParser parser
= new SpelExpressionParser();
//字符串解析
String str = (String) parser.parseExpression("'你好'").getValue();
System.out.println(str);
//整型解析
int intVal = (Integer) parser.parseExpression("0x2F").getValue();
System.out.println(intVal);
//双精度浮点型解析
double doubleVal = (Double) parser.parseExpression("4329759E+22").getValue();
System.out.println(doubleVal);
//布尔型解析
boolean booleanVal = (boolean) parser.parseExpression("true").getValue();
System.out.println(booleanVal);
复制代码
输出结果:正则表达式
你好 47 4.329759E28 truespring
数字支持负数 、小数、科学记数法、八进制数和十六进制数 。 默认状况下,实数使用 Double.parseDouble()
进行表达式类型转换 。数组
在 SpEL 中,咱们可使用对象属性路径(形如类名.属性名.属性名
)来访问对象属性的值。安全
假设有一个帐号类,Account.java:bash
public class Account {
private String name;
private int footballCount;
private Friend friend;
public Account(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setFootballCount(int footballCount) {
this.footballCount = footballCount;
}
public void addFriend(Friend friend) {
this.friend = friend;
}
public int getFootballCount() {
return footballCount;
}
public Friend getFriend() {
return friend;
}
}
复制代码
它包含姓名 name、足球数 footballCount 和一个朋友 friend 属性。friend 属性是一个 Friend 类:ui
public class Friend {
private String name;
public Friend(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
复制代码
解析对象属性表达式:this
//初始化对象
Account account=new Account("Deniro");
account.setFootballCount(10);
account.addFriend(new Friend("Jack"));
//解析器
ExpressionParser parser
= new SpelExpressionParser();
//解析上下文
EvaluationContext context=new StandardEvaluationContext(account);
//获取不一样类型的属性
String name= (String) parser.parseExpression("Name").getValue(context);
System.out.println(name);
int count= (Integer) parser.parseExpression("footballCount+1").getValue(context);
System.out.println(count);
//获取嵌套类中的属性
String friend= (String) parser.parseExpression("friend.name").getValue(context);
System.out.println(friend);
复制代码
输出结果:lua
Deniro 11 Jackspa
数组表达式支持 Java 建立数组的语法,形如 new int[]{3,4,5}
,数组项之间以逗号做为分隔符。**注意:**目前还不支持多维数组。Map 表达式以键值对的方式来定义,形如 {name:'deniro',footballCount:10}
。
//解析器
ExpressionParser parser
= new SpelExpressionParser();
//解析一维数组
int[] oneArray = (int[]) parser.parseExpression("new int[]{3,4,5}").getValue();
System.out.println("一维数组开始:");
for (int i : oneArray) {
System.out.println(i);
}
System.out.println("一维数组结束");
//这里会抛出 SpelParseException
// int[][] twoArray = (int[][]) parser.parseExpression("new int[][]{3,4,5}{3,4,5}")
// .getValue();
//解析 list
List list = (List) parser.parseExpression("{3,4,5}").getValue();
System.out.println("list:" + list);
//解析 Map
Map map = (Map) parser.parseExpression("{account:'deniro',footballCount:10}")
.getValue();
System.out.println("map:" + map);
//解析对象中的 list
final Account account = new Account("Deniro");
Friend friend1 = new Friend("Jack");
Friend friend2 = new Friend("Rose");
List<Friend> friends = new ArrayList<>();
friends.add(friend1);
friends.add(friend2);
account.setFriends(friends);
EvaluationContext context = new StandardEvaluationContext(account);
String friendName = (String) parser.parseExpression("friends[0].name")
.getValue(context);
System.out.println("friendName:" + friendName);
复制代码
从数组与 List 获取值,能够在括号内指定索引来获取,形如上例中的 friends[0]
。Map 中可经过键名来获取,形如 xxx['xxx']
。
输出结果:
一维数组开始: 3 4 5 一维数组结束 list:[3, 4, 5] map:{account=deniro, footballCount=10} friendName:Jack
SpEL 支持调用有访问权限的方法,这些方法包括对象方法、静态方法,并且支持可变方法参数。除此以外,还能够调用 String 类型中的全部可访问方法,好比 String.contains('xxx')
。
//解析器
ExpressionParser parser
= new SpelExpressionParser();
//调用 String 方法
boolean isEmpty = parser.parseExpression("'Hi,everybody'.contains('Hi')").getValue
(Boolean
.class);
System.out.println("isEmpty:" + isEmpty);
/**
* 调用对象相关方法
*/
final Account account = new Account("Deniro");
EvaluationContext context = new StandardEvaluationContext(account);
//调用公开方法
parser.parseExpression("setFootballCount(11)").getValue(context, Boolean
.class);
System.out.println("getFootballCount:" + account.getFootballCount());
//调用私有方法,抛出 SpelEvaluationException: EL1004E: Method call: Method write() cannot be found on net.deniro.spring4.spel.Account type
// parser.parseExpression("write()").getValue(context,Boolean
// .class);
//调用静态方法
parser.parseExpression("read()").getValue(context, Boolean
.class);
//调用待可变参数的方法
parser.parseExpression("addFriendNames('Jack','Rose')").getValue(context, Boolean
.class);
复制代码
**注意:**调用对象的私有方法会抛出异常。
输出结果:
isEmpty:true getFootballCount:11 读书 friendName:Jack friendName:Rose
SpEL 支持 Java 标准操做符:等于、不等于、小于、小等于、大于、大等于、正则表达式和 instanceof 操做符。
//解析器
ExpressionParser parser
= new SpelExpressionParser();
//数值比较
boolean result=parser.parseExpression("2>1").getValue(Boolean.class);
System.out.println("2>1:"+result);
//字符串比较
result=parser.parseExpression("'z'>'a'").getValue(Boolean.class);
System.out.println("'z'>'a':"+result);
//instanceof 运算符
result=parser.parseExpression("'str' instanceof T(String)").getValue(Boolean.class);
System.out.println("'str' 是否为字符串 :"+result);
result=parser.parseExpression("1 instanceof T(Integer)").getValue(Boolean.class);
System.out.println("1 是否为整型 :"+result);
//正则表达式
result=parser.parseExpression("22 matches '\\d{2}'").getValue(Boolean.class);
System.out.println("22 是否为两位数字 :"+result);
复制代码
输出结果:
2>1:true 'z'>'a':true 'str' 是否为字符串 :true 1 是否为整型 :true 22 是否为两位数字 :true
T(Java 包装器类型)
,如整型 T(Integer)
。**注意:**不能使用原生类型,若是这样 T(int)
会返回错误的判断结果。逻辑操做符支持如下操做:
逻辑操做符 | 说明 |
---|---|
and 或 && |
与操做 |
or 或 \|\| |
或操做 |
! |
非操做 |
注意: 在 SpEL 中,不只支持 Java 标准的逻辑操做符,还支持 and 与 or 关键字。
//解析器
ExpressionParser parser
= new SpelExpressionParser();
//与操做
boolean result=parser.parseExpression("true && true").getValue(Boolean.class);
System.out.println("与操做:"+result);
//或操做
result=parser.parseExpression("true || false").getValue(Boolean.class);
System.out.println("或操做:"+result);
parser.parseExpression("true or false").getValue(Boolean.class);
System.out.println("或操做(or 关键字):"+result);
//非操做
result=parser.parseExpression("!false").getValue(Boolean.class);
System.out.println("非操做:"+result);
//抛出 SpelEvaluationException: EL1001E: Type conversion problem, cannot convert from java.lang.Integer to java.lang.Boolean
//parser.parseExpression("!0").getValue(Boolean.class);
复制代码
输出结果:
与操做:true 或操做:true 或操做(or 关键字):true 非操做:true
**注意:**逻辑操做符先后运算结果必须是布尔类型,不然会抛出 SpelEvaluationException。
SpEL 支持 Java 运算操做符,并遵照运算符优先级规则:
运算操做符 | 说明 | 支持的操做数类型 |
---|---|---|
+ | 加法 | 数字、字符串或日期 |
- | 减法 | 数字或日期 |
* | 乘法 | 数字 |
/ |
除法 | 数字 |
% | 取模 | 数字 |
^ | 指数幂 | 数字 |
//加法运算
Integer iResult = parser.parseExpression("2+3").getValue(Integer.class);
System.out.println("加法运算:" + iResult);
String sResult = parser.parseExpression("'Hi,'+'everybody'").getValue(String.class);
System.out.println("字符串拼接运算:" + sResult);
//减法运算
iResult = parser.parseExpression("2-3").getValue(Integer.class);
System.out.println("减法运算:" + iResult);
//乘法运算
iResult = parser.parseExpression("2*3").getValue(Integer.class);
System.out.println("乘法运算:" + iResult);
//除法运算
iResult = parser.parseExpression("4/2").getValue(Integer.class);
System.out.println("除法运算:" + iResult);
Double dResult = parser.parseExpression("4/2.5").getValue(Double.class);
System.out.println("除法运算:" + dResult);
//求余运算
iResult = parser.parseExpression("5%2").getValue(Integer.class);
System.out.println("求余运算:" + iResult);
复制代码
输出结果:
加法运算:5 字符串拼接运算:Hi,everybody 减法运算:-1 乘法运算:6 除法运算:2 除法运算:1.6 求余运算:1
安全导航操做符来源于 Groovy 语言,使用它可以避免空指针异常。通常在访问对象时,须要验证该对象是否为空,使用安全导航操做符就能避免繁琐的空对象验证方法。它的格式是在获取对象属性操做符“.
” 以前加一个 “?
”。
final Account account = new Account("Deniro");
account.addFriend(new Friend("Jack"));
//解析器
ExpressionParser parser
= new SpelExpressionParser();
EvaluationContext context = new StandardEvaluationContext(account);
String friendName=parser.parseExpression("friend?.name").getValue(context,String
.class);
System.out.println("friendName:"+friendName);
//设置为 null
account.setFriend(null);
friendName=parser.parseExpression("friend?.name").getValue(context,String
.class);
//打印出 null
System.out.println("friendName:" + friendName);
复制代码
输出结果:
friendName:Jack friendName:null
这里会先判断 friend 对象是否为空;若是为空,则返回 "null" 字符串;不然返回须要的属性值。
SpEL 支持标准的 Java 三元操做符:<表达式 1>?<表达式 2>:<表达式 3>
ExpressionParser parser
= new SpelExpressionParser();
boolean result=parser.parseExpression("(1+2) == 3?true:false").getValue(Boolean
.class);
System.out.println("result:"+result);
}
复制代码
输出结果:
result:true
Elvis 操做符是在 Groovy 中使用的三元操做符简化版。
在三元操做符中,咱们通常须要写两次变量名,好比下面代码段中的 title:
String title="News";
String actualTitle=(title!=null)?title:"tip";
复制代码
使用 Elvis 操做符后,能够将上述代码段简写为:
title?:"tip"
复制代码
SpEL 支持的 Elvis 操做符格式是:<var>?:<value>
,若是 var 变量为 null,那就取 value 值,不然就取自身的值。因此 Elvis 操做符很适合用于设置默认值。
示例:
final Account account = new Account("Deniro");
//解析器
ExpressionParser parser
= new SpelExpressionParser();
EvaluationContext context = new StandardEvaluationContext(account);
String friendName=parser.parseExpression("name?:'无名'").getValue(context,String
.class);
System.out.println("friendName:"+friendName);
//设置名字为 null
account.setName(null);
friendName=parser.parseExpression("name?:'无名'").getValue(context,String
.class);
System.out.println("friendName:" + friendName);
复制代码
输出结果:
friendName:Deniro friendName:无名
能够经过赋值表达式来设置属性的值,效果等同于调用 setValue() 方法。
final Account account = new Account("Deniro");
//解析器
ExpressionParser parser
= new SpelExpressionParser();
EvaluationContext context = new StandardEvaluationContext(account);
String name=parser.parseExpression("name='Jack'").getValue(context,String
.class);
System.out.println("name:"+name);
复制代码
类型操做符 T 能够从类路径加载指定类名称(全限定名)所对应的 Class 的实例,格式为:T(全限定类名)
,效果等同于 ClassLoader#loadClass()
。
ExpressionParser parser
= new SpelExpressionParser();
//加载 java.lang.Integer
Class integerClass=parser.parseExpression("T(Integer)").getValue(Class
.class);
System.out.println(integerClass==java.lang.Integer.class);
//加载 net.deniro.spring4.spel.Account
Class accountClass=parser.parseExpression("T(net.deniro.spring4.spel.Account)")
.getValue(Class
.class);
System.out.println(accountClass==net.deniro.spring4.spel.Account.class);
//调用类静态方法
double result = (double) parser.parseExpression("T(Math).abs(-2.5)").getValue();
System.out.println("result:" + result);
复制代码
输出结果:
true true result:2.5
咱们还能够直接经过 T 操做符调用类的静态方法,格式为 T(全限定类名).静态方法名
,好比上面例子中求某数的绝对值 T(Math).abs(-2.5)
。
SpEL 中会使用 StandardTypeLocator#findType() 方法来加载类。 findType 方法定义以下:
public Class<?> findType(String typeName) throws EvaluationException {
String nameToLookup = typeName;
try {
return ClassUtils.forName(nameToLookup, this.classLoader);
}
catch (ClassNotFoundException ey) {
// try any registered prefixes before giving up
}
for (String prefix : this.knownPackagePrefixes) {
try {
nameToLookup = prefix + '.' + typeName;
return ClassUtils.forName(nameToLookup, this.classLoader);
}
catch (ClassNotFoundException ex) {
// might be a different prefix
}
}
throw new SpelEvaluationException(SpelMessage.TYPE_NOT_FOUND, typeName);
}
复制代码
可使用 new 操做符来建立一个新对象 。 除了基本类型(如整型、布尔型等)和字符串以外,建立其它类须要指明全限定类名( 包括包路径 ) 。
Account account=parser.parseExpression("new net.deniro.spring4.spel.Account" +
"('Deniro')").getValue(Account.class);
System.out.println("name:"+account.getName());
复制代码
输出结果:
name:Deniro
能够经过 #变量名
来引用在 EvaluationContext 中定义的变量。经过 EvaluationContext#setVariable(name, val)
便可定义新的变量;name 表示变量名,val 表示变量值。
若是变量是集合,好比 list,那么能够经过 #scores.[#this]
来引用集合中的元素。
Account account = new Account("Deniro");
ExpressionParser parser
= new SpelExpressionParser();
EvaluationContext context = new StandardEvaluationContext(account);
//定义一个新变量,名为 newVal
context.setVariable("newVal", "Jack");
//获取变量 newVal 的值,并赋值给 User 的 name 属性
parser.parseExpression("name=#newVal").getValue(context);
System.out.println("getName:" + account.getName());
//this 操做符表示集合中的某个元素
List<Double> scores = new ArrayList<>();
scores.addAll(Arrays.asList(23.1, 82.3, 55.9));
context.setVariable("scores", scores);//在上下文中定义 scores 变量
List<Double> scoresGreat80 = (List<Double>) parser.parseExpression("#scores.?[#this>80]")
.getValue(context);
System.out.println("scoresGreat80:" + scoresGreat80);
复制代码
输出结果:
getName:Jack scoresGreate80:[82.3]
可使用选择表达式来过滤集合,从而生成一个新的符合选择条件的集合 。它的语法是 ?[selectionExpression]
。选择符合条件的结果集的第一个元素的语法为 ^ [selectionExpression]
,选择最后一个元素的语法为 $[selectionExpression]
。选择表达式也可应用于 Map 。
//过滤 list 集合中的元素
final StandardEvaluationContext listContext = new
StandardEvaluationContext(list);
List<Integer> great4List = (List<Integer>) parser.parseExpression("?[#this>4]")
.getValue(listContext);
System.out.println("great4List:" + great4List);
//获取匹配元素中的第一个值
Integer first = (Integer) parser.parseExpression("^[#this>2]")
.getValue(listContext);
System.out.println("first:" + first);
//获取匹配元素中的最后一个值
Integer end = (Integer) parser.parseExpression("$[#this>2]")
.getValue(listContext);
System.out.println("end:" + end);
复制代码
输出结果:
list:[3, 4, 5] great4List:[5] first:3 end:5
对于 List 和 Set ,是针对集合中的每个元素进行比较的;而对于 Map,则能够指定是元素的键(key)仍是元素的值进行比较的。
//过滤 Map
Map<String, Double> rank = new HashMap<>();
rank.put("Deniro", 96.5);
rank.put("Jack", 85.3);
rank.put("Lily", 91.1);
context.setVariable("Rank", rank);
//value 大于 90
Map<String,Double> rankGreat95= (Map<String, Double>) parser.parseExpression
("#Rank.?[value>90]").getValue(context);
System.out.println("rankGreat95:" + rankGreat95);
//key 按字母顺序,排在 L 后面
Map<String,Double> afterL= (Map<String, Double>) parser.parseExpression
("#Rank.?[key>'L']").getValue(context);
System.out.println("afterL:"+afterL);
复制代码
输出结果:
rankGreat95:{Deniro=96.5, Lily=91.1} nameOrder:{Lily=91.1}
经过表达式 ![projectionExpression]
,咱们能够判断集合中每个元素是否符合表达式规则。
List list = (List) parser.parseExpression("{3,4,5}").getValue();
System.out.println("list:" + list);
List<Boolean> isgreat4=(List<Boolean>)parser.parseExpression("![#this>3]")
.getValue(list);
System.out.println("isgreat4:" + isgreat4);
复制代码
输出结果:
isgreat4:[false, true, true]
也能够对 Map 对象进行相似判断。