---
title: "Spring（23）——SPEL表达式（三）"
author: "234390216"
date: "2017-09-18T17:12:58Z"
tags: ["SPEL", "Spring", "el表达式", "介绍", "示例"]
categories: ["开源软件"]
slug: "spring-23-spel"
draft: false
lastmod: "2017-09-18T17:18:15Z"
id: 2393611
url: "https://elim.iteye.com/blog/2393611"
---

### 23.2.16 new对象

SpEl支持我们直接在表达式中使用Java中new对象的语法来new一个对象，在new对象的时候需要我们指定对应类的包名，java.lang包除外。如下示例中我们就在表达式中new了一个java.util.Date对象，然后调用了其toLocaleString()方法。

```
	@Test
	public void test16() {
		ExpressionParser parser = new SpelExpressionParser();
		String currentTime = (String)parser.parseExpression("new java.util.Date().toLocaleString()").getValue();
		System.out.println(currentTime);
	}
```

### [](https://github.com/elim168/elim168.github.io/blob/master/spring/bean/23.spel%E8%A1%A8%E8%BE%BE%E5%BC%8F.md#23217-%E8%B5%8B%E5%80%BC)23.2.17 赋值

SpEl也支持给表达式赋值，其是通过Expression的setValue()方法进行的，在赋值时需要指定rootObject或对应的EvaluationContext。示例如下。

```
@Test
public void test17_1() {
	ExpressionParser parser = new SpelExpressionParser();
	Date d = new java.util.Date();
	//设日期为1号
	parser.parseExpression("date").setValue(d, 1);
	int date = (Integer)parser.parseExpression("date").getValue(d);
	Assert.assertTrue(date == 1);
}
```

其也支持List、Map等的赋值。对于List和Array而言，在进行赋值时是通过元素的索引进行的，且对应的索引必须是存在的。如下示例中我们就将list的第一个元素由0设置为了1。

```
@Test
public void test17_2() {
	ExpressionParser parser = new SpelExpressionParser();
	List<Integer> list = new ArrayList<Integer>(1);
	list.add(0);//添加一个元素0
	EvaluationContext context = new StandardEvaluationContext();
	//添加变量以方便表达式访问
	context.setVariable("list", list);
	//设置第一个元素的值为1
	parser.parseExpression("#list[0]").setValue(context, 1);
	int first = (Integer)parser.parseExpression("#list[0]").getValue(context);
	Assert.assertTrue(first == 1);
}
```

而对于Map的赋值而言是通过key进行的，对应的key在Map中可以先不存在。如下示例就是对Map的赋值。

```
@Test
public void test17_3() {
	ExpressionParser parser = new SpelExpressionParser();
	Map<String, Integer> map = new HashMap<String, Integer>();
	EvaluationContext context = new StandardEvaluationContext();
	//添加变量以方便表达式访问
	context.setVariable("map", map);
	//设置第一个元素的值为1
	parser.parseExpression("#map['key1']").setValue(context, 1);
	int first = (Integer)parser.parseExpression("#map['key1']").getValue(context);
	Assert.assertTrue(first == 1);
}
```

### [](https://github.com/elim168/elim168.github.io/blob/master/spring/bean/23.spel%E8%A1%A8%E8%BE%BE%E5%BC%8F.md#23218-%E8%AE%BF%E9%97%AE%E9%9D%99%E6%80%81%E6%96%B9%E6%B3%95%E6%88%96%E5%B1%9E%E6%80%A7)23.2.18 访问静态方法或属性

SpEl也支持访问类的静态方法或属性，其在进行访问的时候需要使用“T(type)”的形式来表示对应的静态类，其中type表示对应类的全限定名，即包括对应的包名。如下示例中就在表达式中访问了java.util.Calendar的静态属性DATE。

```
@Test
public void test18() {
	ExpressionParser parser = new SpelExpressionParser();
	Assert.assertTrue(parser.parseExpression("T(java.util.Calendar).DATE").getValue(int.class) == 5);
}
```

### [](https://github.com/elim168/elim168.github.io/blob/master/spring/bean/23.spel%E8%A1%A8%E8%BE%BE%E5%BC%8F.md#23219-%E4%BD%BF%E7%94%A8%E5%AD%97%E7%AC%A6%E4%BB%A3%E6%9B%BF%E7%AC%A6%E5%8F%B7)23.2.19 使用字符代替符号

SpEl也允许我们使用某些字符来代替对应的符号，如ge(&gt;=)、gt(&gt;)、lt(&lt;)、le(&lt;=)、eq(==)、ne(!=)、div(/)、mod(%)、not(!)，而且它们都是大小写不敏感的。使用时中间要以空格分开，示例如下。

```
@Test
public void test19() {
	ExpressionParser parser = new SpelExpressionParser();
	Assert.assertTrue(parser.parseExpression("1 lt 2").getValue(boolean.class));//1<2
	Assert.assertTrue(parser.parseExpression("1 le 2").getValue(boolean.class));//1<=2
	Assert.assertTrue(parser.parseExpression("2 gt 1").getValue(boolean.class));//2>1
	Assert.assertTrue(parser.parseExpression("2 ge 1").getValue(boolean.class));//2>=1
	Assert.assertTrue(parser.parseExpression("1 ne 2").getValue(boolean.class));//1!=2
	Assert.assertTrue(parser.parseExpression("not false").getValue(boolean.class));//!false
}
```

### [](https://github.com/elim168/elim168.github.io/blob/master/spring/bean/23.spel%E8%A1%A8%E8%BE%BE%E5%BC%8F.md#23220-%E4%BD%BF%E7%94%A8%E6%AD%A3%E5%88%99%E8%A1%A8%E8%BE%BE%E5%BC%8F)23.2.20 使用正则表达式

SpEl也支持使用正则表达式，其中对应的关键字为match。如下示例中即在表达式中使用了正则表达式，表示123是否匹配正则表达式“\\d{3}”。

```
@Test
public void test20 () {
	ExpressionParser parser = new SpelExpressionParser();
	Assert.assertTrue(parser.parseExpression("123 matches '\\d{3}'").getValue(Boolean.class));//正则匹配三位数字
}
```

### [](https://github.com/elim168/elim168.github.io/blob/master/spring/bean/23.spel%E8%A1%A8%E8%BE%BE%E5%BC%8F.md#23221-%E4%BD%BF%E7%94%A8instanceof)23.2.21 使用instanceof

SpEl也支持在表达式中使用instanceof关键字，以检测对象是否是特定类型的示例。

```
@Test
public void test21 () {
	ExpressionParser parser = new SpelExpressionParser();
	Assert.assertTrue(parser.parseExpression("'123' instanceof T(String)").getValue(Boolean.class));//检测字符串是否是String的实例。
}
```

### [](https://github.com/elim168/elim168.github.io/blob/master/spring/bean/23.spel%E8%A1%A8%E8%BE%BE%E5%BC%8F.md#23222-%E4%B8%89%E7%9B%AE%E8%BF%90%E7%AE%97ifelse)23.2.22 三目运算（if..else..）

SpEl也支持在表达式中使用三目运算符，形式为“exp?trueVal:falseVal”，即如果exp的值为true则返回trueVal，否则返回falseVal。

```
@Test
public void test22 () {
	ExpressionParser parser = new SpelExpressionParser();
	Assert.assertTrue(parser.parseExpression("1>2 ? 1 : 2").getValue(int.class) == 2);//1跟2之间的较大者为2。
	Assert.assertTrue(parser.parseExpression("1<2 ? 2 : 1").getValue(int.class) == 2);//1跟2之间的较大者为2。
}
```

### [](https://github.com/elim168/elim168.github.io/blob/master/spring/bean/23.spel%E8%A1%A8%E8%BE%BE%E5%BC%8F.md#23223-%E8%A1%A8%E8%BE%BE%E5%BC%8F%E6%A8%A1%E6%9D%BF)23.2.23 表达式模板

SpEL还支持在解析表达式时将其当做一个字符串模板进行解析，即可以在表达式中混合普通的文本和特定的表达式块，然后在解析的时候将解析将对其中的表达式块进行计算，以实现模板功能。此功能需要我们在解析表达式时传入一个特定的ParserContext，其可以影响SpEl表达式的解析，对应的模板功能应该传递一个TemplateParserContext。这样Spring在解析对应的SpEl表达式时将会把其当做一个模板，然后对其中“#{exp}”形式的表达式进行计算。如下示例就是表达式模板的一个简单用法，其中使用#{}包起来的表达式会被当做一个普通的SpEl表达式进行计算以得出当前的年份，再进行替换，所以所得结果将是“the year is 2014”。

```
@Test
public void test23 () {
	//the year is 2014
	String expressionStr = "the year is #{T(java.util.Calendar).getInstance().get(T(java.util.Calendar).YEAR)}";
	ExpressionParser parser = new SpelExpressionParser();
	Expression expression = parser.parseExpression(expressionStr, new TemplateParserContext());
	Assert.assertTrue(expression.getValue().equals("the year is 2014"));
}
```

### [](https://github.com/elim168/elim168.github.io/blob/master/spring/bean/23.spel%E8%A1%A8%E8%BE%BE%E5%BC%8F.md#23224-%E8%AE%BE%E7%BD%AE%E9%BB%98%E8%AE%A4%E5%80%BC)