Spring Espresdsion Language
Spring表達式語言(簡稱SpEL)是一個支持查詢并在運行時操縱一個對象圖的功能強大的表達式語言。SpEL語言的語法類似于統一EL,但提供了更多的功能,最主要的是顯式方法調用和基本字符串模板函數。
同很多可用的Java 表達式語言相比,例如OGNL,MVEL和JBoss EL,SpEL的誕生是為了給Spring社區提供一個可以給Spring目錄中所有產品提供單一良好支持的表達式語言。其語言特性由Spring目錄中的項目需求驅動,包括基于eclipse的SpringSource套件中的代碼補全工具需求。也就是說,SpEL是一個基于技術中立的API允許需要時與其他表達式語言集成。
SpEL作為Spring目錄中表達式求值的基礎,它并不是直接依賴于Spring而是可以被獨立使用。為了能夠自包含,本章中的許多示例把SpEL作為一個獨立的表達式語言來使用。這就需要創建一些如解析器的引導基礎組件類。大多數Spring用戶只需要為求值編寫表達式字符串而不需要關心這些基礎組件
SpEL 的功能特性:
- 字符表達式
- 布爾和關系操作符
- 正則表達式
- 類表達式
- 訪問properties,arrays,lists,maps
- 方法調用
- 關系操作符
- 賦值
- 調用構造器
- 三元操作符
- 變量
- 用戶自定義函數
- 集合投影
- 集合選擇
- 模板表達式
使用 spring 表達式語言
- 新建一個Maven Web項目,添加依賴,pom.xml如下所示:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.ceshi.test</groupId>
<artifactId>Spring053</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>Spring053</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<spring.version>4.3.0.RELEASE</spring.version>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
<version>4.10</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.9</version>
</dependency>
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib</artifactId>
<version>3.2.4</version>
</dependency>
</dependencies>
</project>
- 為了IOC,定義了用戶類User.java與Order.java,如下:
package com.ceshi.test.Spring053;
/**
* 訂單類
*
*/
public class Order {
/**
* 訂單名稱
*/
private String orderName;
/*
* 用戶姓名
*/
private String userName;
/**
* 用戶對象
*/
private User customer;
public String getOrderName() {
return orderName;
}
public void setOrderName(String orderName) {
this.orderName = orderName;
}
public User getCustomer() {
return customer;
}
public void setCustomer(User customer) {
this.customer = customer;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
@Override
public String toString() {
return "訂單名:"+this.getOrderName()+",姓名:"+this.getUserName()+",編號:"+this.getCustomer().getId();
}
}
package com.ceshi.test.Spring053.spel01;
/**
* 訂單類
*
*/
public class Order {
/**
* 訂單名稱
*/
private String orderName;
/*
* 用戶姓名
*/
private String userName;
/**
* 用戶對象
*/
private User customer;
public String getOrderName() {
return orderName;
}
public void setOrderName(String orderName) {
this.orderName = orderName;
}
public User getCustomer() {
return customer;
}
public void setCustomer(User customer) {
this.customer = customer;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
}
- 編寫容器初始化的配置文件spel01.xml,內容如下:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.3.xsd">
<bean id="gyl" class="com.ceshi.test.Spring053.spel01.User" p:id="9527">
<property name="name" value="張三">
</property>
</bean>
<bean id="order001" class="com.ceshi.test.Spring053.spel01.Order">
<property name="customer" ref="gyl"></property>
<property name="name" value="#{gyl.name}"></property>
<property name="orderName" value='#{"Apples".toUpperCase()}'></property>
</bean>
</beans>
復制代碼
在配置文件中,出現了#{}形式的表達式,我們就稱為Spel表達式。#{gyl.name}作用是找到名稱為gyl的bean取出中間的name值;#{"Apples".toUpperCase()}把字符串Apples轉換成大寫并輸出。
- 取出bean測試
package com.ceshi.test.Spring053.spel01;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test {
public static void main(String[] args) {
ApplicationContext ctx=new ClassPathXmlApplicationContext("spel01.xml");
Order order=ctx.getBean("order001",Order.class);
System.out.println(order);
}
}
//運行結果:訂單名:APPLES,姓名:張三,編號:9527
SpEL表達式Hello World!
Spring表達式語言(SpEL)從3.X開始支持,它是一種能夠支持運行時查詢和操作對象圖的強大的表達式,其表達式語法類似于統一表達式語言。
SpEL支持如下表達式:
- 基本表達式:字面量表達式、關系,邏輯與算數運算表達式、字符串連接及截取表達式、三目運算、正則表達式、括號優先級表達式;
- 類相關表達式:類類型表達式、類實例化、instanceof表達式、變量定義及引用、賦值表達式、自定義函數、對象屬性存取及安全導航表達式、對象方法調用、Bean引用;
- 集合相關表達式:內聯List、內聯數組、集合,字典訪問、列表,字典,數組修改、集合投影、集合選擇;不支持多維內聯數組初始化;不支持內聯字典定義;
- 其他表達式:模板表達式.
package com.ceshi.test.Spring053.spel02;
import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
public class Test {
public static void main(String[] args) {
//創建SpEL表達式的解析器
ExpressionParser parser=new SpelExpressionParser();
//解析表達式'Hello '+' World!'
Expression exp=parser.parseExpression("'Hello '+' World!'");
//取出解析結果
String result=exp.getValue().toString();
//輸出結果
System.out.println(result);
}
}
SpEL 表達式的運用
支持的文字表達的類型是字符串,日期,數值(整型,實型,和十六進制),布爾和空。字符串是由單引號分隔。使用反斜杠字符轉移把一個單引號字符本身放在字符串中。
//創建SpEL表達式的解析器
ExpressionParser ep= new SpelExpressionParser();
System.out.println(ep.parseExpression("'HelloWorld'").getValue());
System.out.println(ep.parseExpression("0xffffff").getValue());
System.out.println(ep.parseExpression("1.234345e+3").getValue());
System.out.println(ep.parseExpression("new java.util.Date()").getValue());
ExpressionParser parser=new SpelExpressionParser();
User user=new User(9527,"張三");
//解析表達式需要的上下文,解析時有一個默認的上下文
EvaluationContext ctx = new StandardEvaluationContext();
//在上下文中設置變量,變量名為user,內容為user對象
ctx.setVariable("user", user);
//從用戶對象中獲得id,獲得解析后的值在ctx上下文中
//User類在前面已定義,這里增加了一個有參構造方法。上面的示例是調用方法,其實可以這樣:引用對象屬性,只需使用一個句點來表示一個嵌套的屬性值
int id = (Integer) parser.parseExpression("#user.getId()").getValue(ctx);
System.out.println(id);
//運行結果HelloWorld
16777215
1234.345
Fri Jul 01 14:50:59 CST 2017
9527
數組:
String[] students=new String[]{"tom","jack","rose","mark","lucy"};
ctx.setVariable("students", students);
String student = parser.parseExpression("#students[3]").getValue(ctx,
String.class);
System.out.println(student);
大致使用都是類似的 parser.parseExpression(" 表達式 ").getValue( 上下文, class);
parser.parseExpression(" 表達式 ").getValue(class);
/**關系運算符*/
//true
boolean trueValue1 = parser.parseExpression("2 == 2").getValue(Boolean.class);
//false
boolean falseValue1 = parser.parseExpression("2 < -5.0").getValue(Boolean.class);
//true
boolean trueValue2 = parser.parseExpression("'black' < 'block'").getValue(Boolean.class);
//false,字符xyz是否為int類型
boolean falseValue2 = parser.parseExpression("'xyz' instanceof T(int)").getValue(Boolean.class);
//true,正則是否匹配
boolean trueValue3 =parser.parseExpression("'5.00' matches '^-?\\d+(\\.\\d{2})?$'").getValue(Boolean.class);
//false
boolean falseValue3=parser.parseExpression("'5.0067' matches '^-?\\d+(\\.\\d{2})?$'").getValue(Boolean.class);
/**邏輯運算*/
//false
boolean falseValue4 = parser.parseExpression("true and false").getValue(Boolean.class);
//true,isMember方法用于測試是否為某個對象的成員
String expression = "isMember('Nikola Tesla') and isMember('Mihajlo Pupin')";
boolean trueValue4 = parser.parseExpression(expression).getValue(Boolean.class);
// -- OR 或運算--
//true
boolean trueValue5 = parser.parseExpression("true or false").getValue(Boolean.class);
//true
String expression1 = "isMember('Nikola Tesla') or isMember('Albert Einstein')";
boolean trueValue6 = parser.parseExpression(expression).getValue( Boolean.class);
//false
boolean falseValue5 = parser.parseExpression("!true").getValue(Boolean.class);
//false
String expression2 = "isMember('Nikola Tesla') and !isMember('Mihajlo Pupin')";
boolean falseValue6 = parser.parseExpression(expression).getValue(Boolean.class);
// Addition
int two = parser.parseExpression("1 + 1").getValue(Integer.class);
// 2
String testString =
parser.parseExpression("'test' + ' ' + 'string'").getValue(String.class); // 'test string'
// Subtraction
int four = parser.parseExpression("1 - -3").getValue(Integer.class); // 4
double d = parser.parseExpression("1000.00 - 1e4").getValue(Double.class); // -9000
// Multiplication
int six = parser.parseExpression("-2 * -3").getValue(Integer.class); // 6
double twentyFour = parser.parseExpression("2.0 * 3e0 * 4").getValue(Double.class); // 24.0
// Division
int minusTwo = parser.parseExpression("6 / -3").getValue(Integer.class); // -2
double one = parser.parseExpression("8.0 / 4e0 / 2").getValue(Double.class); // 1.0
// Modulus
int three = parser.parseExpression("7 % 4").getValue(Integer.class); // 3
int one = parser.parseExpression("8 / 5 % 2").getValue(Integer.class); // 1
// Operator precedence
int minusTwentyOne = parser.parseExpression("1+2-3*8").getValue(Integer.class); // -21
基于 XML 配置定義 Bean
<bean id="gyl" class="com.ceshi.test.Spring053.spel01.User" p:id="9527">
<property name="name" value="張三">
</property>
</bean>
<bean id="order001" class="com.ceshi.test.Spring053.spel01.Order">
<property name="customer" ref="gyl"></property>
<property name="userName" value="#{gyl.name}"></property>
<property name="orderName" value='#{"Apples".toUpperCase()}'></property>
</bean>
<bean id="numberGuess" class="org.spring.samples.NumberGuess">
<!--調用靜態方法random() -->
<property name="randomNumber" value="#{ T(java.lang.Math).random() * 100.0 }" />
</bean>
<bean id="taxCalculator" class="org.spring.samples.TaxCalculator">
<property name="defaultLocale" value="#{ systemProperties['user.region'] }" />
</bean>
<bean id="numberGuess" class="org.spring.samples.NumberGuess">
<property name="randomNumber" value="#{ T(java.lang.Math).random() * 100.0 }" />
</bean>
<bean id="shapeGuess" class="org.spring.samples.ShapeGuess">
<property name="initialShapeSeed" value="#{ numberGuess.randomNumber }" />
</bean>
基于注解配置:
package com.ceshi.test.Spring053.spel03;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
/**
* 用戶類
*/
@Component("user1")
public class User {
/**
* 編號
*/
@Value("#{9527+100}")
private int id;
/**
* 姓名
*/
@Value("#{'Hello'.toUpperCase()}")
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}