前言
SpEL(Spring Expression Language),即Spring表達式語言,是比JSP的EL更強大的一種表達式語言。為什么要總結SpEL,因為它可以在運行時查詢和操作數據,尤其是數組列表型數據,因此可以縮減代碼量,優化代碼結構。個人認為很有用。
一. 用法
SpEL有三種用法,一種是在注解@Value中;一種是XML配置;最后一種是在代碼塊中使用Expression。
- @Value
//@Value能修飾成員變量和方法形參 //#{}內就是表達式的內容 @Value("#{表達式}") public String arg;
- <bean>配置
<bean id="xxx" class="com.java.XXXXX.xx">
<!-- 同@Value,#{}內是表達式的值,可放在property或constructor-arg內 -->
<property name="arg" value="#{表達式}">
</bean>
- Expression
import org.springframework.expression.Expression; import org.springframework.expression.ExpressionParser; import org.springframework.expression.spel.standard.SpelExpressionParser; import org.springframework.expression.spel.support.StandardEvaluationContext; public class SpELTest { public static void main(String[] args) { //創建ExpressionParser解析表達式 ExpressionParser parser = new SpelExpressionParser(); //表達式放置 Expression exp = parser.parseExpression("表達式"); //執行表達式,默認容器是spring本身的容器:ApplicationContext Object value = exp.getValue(); /**如果使用其他的容器,則用下面的方法*/ //創建一個虛擬的容器EvaluationContext StandardEvaluationContext ctx = new StandardEvaluationContext(); //向容器內添加bean BeanA beanA = new BeanA(); ctx.setVariable("bean_id", beanA); //setRootObject並非必須;一個EvaluationContext只能有一個RootObject,引用它的屬性時,可以不加前綴 ctx.setRootObject(XXX); //getValue有參數ctx,從新的容器中根據SpEL表達式獲取所需的值 Object value = exp.getValue(ctx); } }
二. 表達式語法
1、字面量賦值
<!-- 整數 --> <property name="count" value="#{5}" /> <!-- 小數 --> <property name="frequency" value="#{13.2}" /> <!-- 科學計數法 --> <property name="capacity" value="#{1e4}" /> <!-- 字符串 #{"字符串"} 或 #{'字符串'} --> <property name="name" value="#{'我是字符串'}" /> <!-- Boolean --> <property name="enabled" value="#{false}" />
注: 1)字面量賦值必須要和對應的屬性類型兼容,否則會報異常。2)一般情況下我們不會使用 SpEL字面量賦值,因為我們可以直接賦值。
2.引用Bean、屬性和方法(必須是public修飾的)
<property name="car" value="#{car}" /> <!-- 引用其他對象的屬性 --> <property name="carName" value="#{car.name}" /> <!-- 引用其他對象的方法 --> <property name="carPrint" value="#{car.print()}" />
3.運算符
3.1 算術運算符:+,-,*,/,%,^
<!-- 3 --> <property name="num" value="#{2+1}" /> <!-- 1 --> <property name="num" value="#{2-1}" /> <!-- 4 --> <property name="num" value="#{2*2}" /> <!-- 3 --> <property name="num" value="#{9/3}" /> <!-- 1 --> <property name="num" value="#{10%3}" /> <!-- 1000 --> <property name="num" value="#{10^3}" />
3.2 字符串連接符:+
<!-- 10年3個月 --> <property name="numStr" value="#{10+'年'+3+'個月'}" />
3.3 比較運算符:<(<),>(>),==,<=,>=,lt,gt,eq,le,ge
<!-- false --> <property name="numBool" value="#{10<0}" /> <!-- false --> <property name="numBool" value="#{10 lt 0}" /> <!-- true --> <property name="numBool" value="#{10>0}" /> <!-- true --> <property name="numBool" value="#{10 gt 0}" /> <!-- true --> <property name="numBool" value="#{10==10}" /> <!-- true --> <property name="numBool" value="#{10 eq 10}" /> <!-- false --> <property name="numBool" value="#{10<=0}" /> <!-- false --> <property name="numBool" value="#{10 le 0}" /> <!-- true --> <property name="numBool" value="#{10>=0}" /> <!-- true --> <property name="numBool" value="#{10 ge 0}" />
3.4 邏輯運算符:and,or,not,&&(&&),||,!
<!-- false --> <property name="numBool" value="#{true and false}" /> <!-- false --> <property name="numBool" value="#{true&&false}" /> <!-- true --> <property name="numBool" value="#{true or false}" /> <!-- true --> <property name="numBool" value="#{true||false}" /> <!-- false --> <property name="numBool" value="#{not true}" /> <!-- false --> <property name="numBool" value="#{!true}" />
3.5 條件運算符:?true:false
<!-- 真 --> <property name="numStr" value="#{(10>3)?'真':'假'}" />
3.6 正則表達式:matches
<!-- true -->
<property name="numBool" value="#{user.email matches '[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+.[a-zA-Z]{2,4}'}" />
4.調用靜態方法或靜態屬性
通過 T() 調用一個類的靜態方法,它將返回一個 Class Object,然后再調用相應的方法或屬性:
<!-- 3.141592653589793 -->
<property name="PI" value="#{T(java.lang.Math).PI}" />
5.獲取容器內的變量,可以使用“#bean_id”來獲取。有兩個特殊的變量,可以直接使用。
this 使用當前正在計算的上下文 root 引用容器的root對象 String result2 = parser.parseExpression("#root").getValue(ctx, String.class); String s = new String("abcdef"); ctx.setVariable("abc",s); //取id為abc的bean,然后調用其中的substring方法 parser.parseExpression("#abc.substring(0,1)").getValue(ctx, String.class);
6.方法調用
與Java代碼沒有什么區別,可見上面的例子,可以自定義方法,如下:
Method parseInt = Integer.class.getDeclaredMethod("parseInt", String.class); ctx.registerFunction("parseInt", parseInt); ctx.setVariable("parseInt2", parseInt);
“registerFunction”和“setVariable”都可以注冊自定義函數,但是兩個方法的含義不一樣,推薦使用“registerFunction”方法注冊自定義函數。
7.Elvis運算符
是三目運算符的特殊寫法,可以避免null報錯的情況
name != null? name : "other" //簡寫為: name?:"other"
8.安全保證
為了避免操作對象本身可能為null,取屬性時報錯,定義語法
語法: “對象?.變量|方法”
list?.length
9.直接使用java代碼new/instance of
此方法只能是java.lang 下的類才可以省略包名
Expression exp = parser.parseExpression("new Spring('Hello World')");
10.集合定義
使用“{表達式,……}”定義List,如“{1,2,3}”
對於字面量表達式列表,SpEL會使用java.util.Collections.unmodifiableList 方法將列表設置為不可修改。
對於列表中只要有一個不是字面量表達式,將只返回原始List
// 不會進行不可修改處理,也就是可以修改
List<list> result3 = parser.parseExpression(expression3).getValue(List.class); result3.get(0).set(0, 1); List<Integer> result1 = parser.parseExpression("{1,2,3}").getValue(List.class);
11.集合訪問
SpEL目前支持所有集合類型和字典類型的元素訪問
語法:“集合[索引]”、“map[key]”
EvaluationContext context = new StandardEvaluationContext(); //即list.get(0) int result1 = parser.parseExpression("{1,2,3}[0]").getValue(int.class); //list獲取某一項 Collection<Integer> collection = new HashSet<Integer>(); collection.add(1); collection.add(2); context.setVariable("collection", collection); int result2 = parser.parseExpression("#collection[1]").getValue(context, int.class); //map獲取 Map<String, Integer> map = new HashMap<String, Integer>(); map.put("a", 1); context.setVariable("map", map); int result3 = parser.parseExpression("#map['a']").getValue(context, int.class);
12. 集合修改
可以使用賦值表達式或Expression接口的setValue方法修改;
//賦值語句 int result = parser.parseExpression("#array[1] = 3").getValue(context, int.class); //serValue方法 parser.parseExpression("#array[2]").setValue(context, 4);
13. 集合選擇 通過一定的規則對及格進行篩選,構造出另一個集合
語法:“(list|map).?[選擇表達式]” 選擇表達式結果必須是boolean類型,如果true則選擇的元素將添加到新集合中,false將不添加到新集合中 parser.parseExpression("#collection.?[#this>2]").getValue(context, Collection.class); 上面的例子從數字的collection集合中選出數字大於2的值,重新組裝成了一個新的集合
14.上面的例子從數字的collection集合中選出數字大於2的值,重新組裝成了一個新的集合 根據集合中的元素中通過選擇來構造另一個集合,該集合和原集合具有相同數量的元素 語法:“SpEL使用“(list|map).![投影表達式]”
public class Book { public String name; //書名 public String author; //作者 public String publisher; //出版社 public double price; //售價 public boolean favorite; //是否喜歡 } public class BookList { @Autowired protected ArrayList<Book> list = new ArrayList<Book>() ; protected int num = 0; } 將BookList的實例映射為bean:readList,在另一個bean中注入時,進行投影 //從readList的list下篩選出favorite為true的子集合,再將他們的name字段投為新的list @Value("#{list.?[favorite eq true].![name]}") private ArrayList<String> favoriteBookName;
15.Bean引用:
SpEL支持使用“@”符號來引用Bean,在引用Bean時需要使用BeanResolver接口實現來查找Bean,Spring提供BeanFactoryResolver實現;
@Test public void testBeanExpression() { ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(); ctx.refresh(); ExpressionParser parser = new SpelExpressionParser(); StandardEvaluationContext context = new StandardEvaluationContext(); context.setBeanResolver(new BeanFactoryResolver(ctx)); Properties result1 = parser.parseExpression("@systemProperties").getValue(context, Properties.class); Assert.assertEquals(System.getProperties(), result1); }
原文地址:https://www.jianshu.com/p/e0b50053b5d3