本篇講述了Spring Expression Language —— 即Spring3中功能豐富強大的表達式語言,簡稱SpEL。SpEL是相似於OGNL和JSF EL的表達式語言,可以在運行時構建複雜表達式,存取對象屬性、對象方法調用等。全部的SpEL都支持XML和Annotation兩種方式,格式:#{ SpEL expression }java
這個例子將展現如何利用SpEL注入String、Integer、Bean到屬性中。spring
1. Spring El的依賴包express
首先在Maven的pom.xml中加入依賴包,這樣會自動下載SpEL的依賴。ide
文件:pom.xml函數
<dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>3.2.4.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>3.2.4.RELEASE</version> </dependency> </dependencies>
2. Spring Beanthis
接下來寫兩個簡單的Bean,稍後會用SpEL注入value到屬性中。spa
Item.java以下:code
package com.lei.demo.el; public class Item { private String name; private int total; //getter and setter... }
Customer.java以下:component
package com.lei.demo.el; public class Customer { private Item item; private String itemName; @Override public String toString() { return "itemName=" +this.itemName+" "+"Item.total="+this.item.getTotal(); } //getter and setter... }
3. Spring EL——XMLxml
SpEL格式爲#{ SpEL expression },xml配置見下。
文件:Spring-EL.xml
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> <bean id="itemBean" class="com.lei.demo.el.Item"> <property name="name" value="itemA" /> <property name="total" value="10" /> </bean> <bean id="customerBean" class="com.lei.demo.el.Customer"> <property name="item" value="#{itemBean}" /> <property name="itemName" value="#{itemBean.name}" /> </bean> </beans>
註解:
1. #{itemBean}——將itemBean注入到customerBean的item屬性中。
2. #{itemBean.name}——將itemBean 的name屬性,注入到customerBean的屬性itemName中。
4. Spring EL——Annotation
SpEL的Annotation版本。
注意:要在Annotation中使用SpEL,必需要經過annotation註冊組件。若是你在xml中註冊了bean和在java class中定義了@Value,@Value在運行時將失敗。
Item.java以下:
package com.lei.demo.el; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; @Component("itemBean") public class Item { @Value("itemA")//直接注入String private String name; @Value("10")//直接注入integer private int total; //getter and setter... }
Customer.java以下:
package com.lei.demo.el; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; @Component("customerBean") public class Customer { @Value("#{itemBean}") private Item item; @Value("#{itemBean.name}") private String itemName; //getter and setter... }
Xml中配置組件自動掃描
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <context:component-scan base-package="com.lei.demo.el" /> </beans>
在Annotation模式中,用@Value定義EL。在這種狀況下,直接注入一個String和integer值到itemBean中,而後注入itemBean到customerBean中。
5. 輸出結果
App.java以下:
package com.lei.demo.el; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class App { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("Spring-EL.xml"); Customer obj = (Customer) context.getBean("customerBean"); System.out.println(obj); } }
輸出結果以下:itemName=itemA item.total=10
SpEL容許開發者用El運行方法函數,而且容許將方法返回值注入到屬性中。
此段落演示用@Value註釋,完成SpEL方法調用。
Customer.java以下:
package com.lei.demo.el; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; @Component("customerBean") public class Customer { @Value("#{'lei'.toUpperCase()}") private String name; @Value("#{priceBean.getSpecialPrice()}") private double amount; //getter and setter...省略 @Override public String toString() { return "Customer [name=" + name + ", amount=" + amount + "]"; } }
Price.java以下:
package com.lei.demo.el; import org.springframework.stereotype.Component; @Component("priceBean") public class Price { public double getSpecialPrice() { return new Double(99.99); } }
輸出結果:Customer[name=LEI,amount=99.99]
上例中,如下語句調用toUpperCase()方法
@Value("#{'lei'.toUpperCase()}") private String name;
上例中,如下語句調用priceBean中的getSpecialPrice()方法
@Value("#{priceBean.getSpecialPrice()}") private double amount;
在XMl中配置以下,效果相同
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> <bean id="customerBean" class="com.leidemo.el.Customer"> <property name="name" value="#{'lei'.toUpperCase()}" /> <property name="amount" value="#{priceBean.getSpecialPrice()}" /> </bean> <bean id="priceBean" class="com.lei.demo.el.Price" /> </beans>
Spring EL 支持大多數的數學操做符、邏輯操做符、關係操做符。
1.關係操做符
包括:等於 (==, eq),不等於 (!=, ne),小於 (<, lt),,小於等於(<= , le),大於(>, gt),大於等於 (>=, ge)
2.邏輯操做符
包括:and,or,and not(!)
3.數學操做符
包括:加 (+),減 (-),乘 (*),除 (/),取模 (%),冪指數 (^)。
Numer.java以下
package com.lei.demo.el; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; @Component("numberBean") public class Number { @Value("999") private int no; public int getNo() { return no; } public void setNo(int no) { this.no = no; } }
Customer.java以下
package com.lei.demo.el; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; @Component("customerBean") public class Customer { //Relational operators @Value("#{1 == 1}") //true private boolean testEqual; @Value("#{1 != 1}") //false private boolean testNotEqual; @Value("#{1 < 1}") //false private boolean testLessThan; @Value("#{1 <= 1}") //true private boolean testLessThanOrEqual; @Value("#{1 > 1}") //false private boolean testGreaterThan; @Value("#{1 >= 1}") //true private boolean testGreaterThanOrEqual; //Logical operators , numberBean.no == 999 @Value("#{numberBean.no == 999 and numberBean.no < 900}") //false private boolean testAnd; @Value("#{numberBean.no == 999 or numberBean.no < 900}") //true private boolean testOr; @Value("#{!(numberBean.no == 999)}") //false private boolean testNot; //Mathematical operators @Value("#{1 + 1}") //2.0 private double testAdd; @Value("#{'1' + '@' + '1'}") //1@1 private String testAddString; @Value("#{1 - 1}") //0.0 private double testSubtraction; @Value("#{1 * 1}") //1.0 private double testMultiplication; @Value("#{10 / 2}") //5.0 private double testDivision; @Value("#{10 % 10}") //0.0 private double testModulus ; @Value("#{2 ^ 2}") //4.0 private double testExponentialPower; @Override public String toString() { return "Customer [testEqual=" + testEqual + ", testNotEqual=" + testNotEqual + ", testLessThan=" + testLessThan + ", testLessThanOrEqual=" + testLessThanOrEqual + ", testGreaterThan=" + testGreaterThan + ", testGreaterThanOrEqual=" + testGreaterThanOrEqual + ", testAnd=" + testAnd + ", testOr=" + testOr + ", testNot=" + testNot + ", testAdd=" + testAdd + ", testAddString=" + testAddString + ", testSubtraction=" + testSubtraction + ", testMultiplication=" + testMultiplication + ", testDivision=" + testDivision + ", testModulus=" + testModulus + ", testExponentialPower=" + testExponentialPower + "]"; } }
運行以下代碼:
Customer obj = (Customer) context.getBean("customerBean");
System.out.println(obj);
結果以下:
Customer [ testEqual=true, testNotEqual=false, testLessThan=false, testLessThanOrEqual=true, testGreaterThan=false, testGreaterThanOrEqual=true, testAnd=false, testOr=true, testNot=false, testAdd=2.0, testAddString=1@1, testSubtraction=0.0, testMultiplication=1.0, testDivision=5.0, testModulus=0.0, testExponentialPower=4.0 ]
如下是等同的xml配置。
注意,相似小於號「<」,或者小於等於「<=」,在xml中是不直接支持的,必須用等同的文本表示方法表示,
例如,「<」用「lt」替換;「<=」用「le」替換,等等。
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> <bean id="customerBean" class="com.lei.demo.el.Customer"> <property name="testEqual" value="#{1 == 1}" /> <property name="testNotEqual" value="#{1 != 1}" /> <property name="testLessThan" value="#{1 lt 1}" /> <property name="testLessThanOrEqual" value="#{1 le 1}" /> <property name="testGreaterThan" value="#{1 > 1}" /> <property name="testGreaterThanOrEqual" value="#{1 >= 1}" /> <property name="testAnd" value="#{numberBean.no == 999 and numberBean.no lt 900}" /> <property name="testOr" value="#{numberBean.no == 999 or numberBean.no lt 900}" /> <property name="testNot" value="#{!(numberBean.no == 999)}" /> <property name="testAdd" value="#{1 + 1}" /> <property name="testAddString" value="#{'1' + '@' + '1'}" /> <property name="testSubtraction" value="#{1 - 1}" /> <property name="testMultiplication" value="#{1 * 1}" /> <property name="testDivision" value="#{10 / 2}" /> <property name="testModulus" value="#{10 % 10}" /> <property name="testExponentialPower" value="#{2 ^ 2}" /> </bean> <bean id="numberBean" class="com.lei.demo.el.Number"> <property name="no" value="999" /> </bean> </beans>
SpEL支持三目運算符,以此來實現條件語句。
Item.java以下:
package com.lei.demo.el; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; @Component("itemBean") public class Item { @Value("99") private int qtyOnHand; public int getQtyOnHand() { return qtyOnHand; } public void setQtyOnHand(int qtyOnHand) { this.qtyOnHand = qtyOnHand; } }
Customer.java以下:
package com.lei.demo.el; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; @Component("customerBean") public class Customer { @Value("#{itemBean.qtyOnHand < 100 ? true : false}") private boolean warning; public boolean isWarning() { return warning; } public void setWarning(boolean warning) { this.warning = warning; } @Override public String toString() { return "Customer [warning=" + warning + "]"; } }
輸出:Customer [warning=true]
Xml配置以下,注意:應該用「<;」代替小於號「<」
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> <bean id="customerBean" class="com.lei.demo.el.Customer"> <property name="warning" value="#{itemBean.qtyOnHand < 100 ? true : false}" /> </bean> <bean id="itemBean" class="com.lei.demo.el.Item"> <property name="qtyOnHand" value="99" /> </bean> </beans>
輸出:Customer [warning=true]
此段演示SpEL怎樣從List、Map集合中取值,簡單示例以下:
//get map where key = 'MapA' @Value("#{testBean.map['MapA']}") private String mapA; //get first value from list, list is 0-based. @Value("#{testBean.list[0]}") private String list;
首先,建立一個HashMap和ArrayList,並初始化一些值。
Test.java以下:
package com.lei.demo.el; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.springframework.stereotype.Component; @Component("testBean") public class Test { private Map<String, String> map; private List<String> list; public Test() { map = new HashMap<String, String>(); map.put("MapA", "This is A"); map.put("MapB", "This is B"); map.put("MapC", "This is C"); list = new ArrayList<String>(); list.add("List0"); list.add("List1"); list.add("List2"); } public Map<String, String> getMap() { return map; } public void setMap(Map<String, String> map) { this.map = map; } public List<String> getList() { return list; } public void setList(List<String> list) { this.list = list; } }
而後,用SpEL取值,Customer.java以下
package com.lei.demo.el; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; @Component("customerBean") public class Customer { @Value("#{testBean.map['MapA']}") private String mapA; @Value("#{testBean.list[0]}") private String list; public String getMapA() { return mapA; } public void setMapA(String mapA) { this.mapA = mapA; } public String getList() { return list; } public void setList(String list) { this.list = list; } @Override public String toString() { return "Customer [mapA=" + mapA + ", list=" + list + "]"; } }
調用代碼以下:
Customer obj = (Customer) context.getBean("customerBean");
System.out.println(obj);
輸出結果:Customer [mapA=This is A, list=List0]
Xml配置以下:
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> <bean id="customerBean" class="com.lei.demo.el.Customer"> <property name="mapA" value="#{testBean.map['MapA']}" /> <property name="list" value="#{testBean.list[0]}" /> </bean> <bean id="testBean" class="com.lei.demo.el.Test" /> </beans>