首页 文章资讯内容详情

Spring3系列6 - Spring 表达式语言(Spring EL)

2026-06-01 3 花语

本文内容纲要:

-Spring3系列6-Spring表达式语言(SpringEL) -一、第一个SpringEL例子——HelloWorldDemo -二、SpringELMethodInvocation——SpEL方法调用 -三、SpringELOperators——SpEL操作符 -四、SpringEL三目操作符condition?true:false -五、SpringEL操作List、Map集合取值 -一、第一个SpringEL例子——HelloWorldDemo -二、SpringELMethodInvocation——SpEL方法调用 -1.SpringELMethodInvocation之Annotation -2.SpringELMethodInvocation之XML -三、SpringELOperators——SpEL操作符 -1.SpringELOperators之Annotation -2.SpringELOperators之XML -四、SpringEL三目操作符condition?true:false -1.Annotation -2.XMl -五、SpringEL操作List、Map集合取值 -1.Annotation -2.XML

Spring3系列6-Spring表达式语言(SpringEL)

本篇讲述了SpringExpressionLanguage——即Spring3中功能丰富强大的表达式语言,简称SpEL。SpEL是类似于OGNL和JSFEL的表达式语言,能够在运行时构建复杂表达式,存取对象属性、对象方法调用等。所有的SpEL都支持XML和Annotation两种方式,格式:#{SpELexpression}

一、第一个SpringEL例子——HelloWorldDemo

二、SpringELMethodInvocation——SpEL方法调用

三、SpringELOperators——SpEL操作符

四、SpringEL三目操作符condition?true:false

五、SpringEL操作List、Map集合取值

一、第一个SpringEL例子——HelloWorldDemo

这个例子将展示如何利用SpEL注入String、Integer、Bean到属性中。

1.SpringEl****的依赖包

首先在Maven的pom.xml中加入依赖包,这样会自动下载SpEL的依赖。

文件: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.SpringBean

接下来写两个简单的Bean,稍后会用SpEL注入value到属性中。

Item.java如下:

packagecom.lei.demo.el; publicclassItem{ privateStringname; privateinttotal; //getterandsetter... }

Customer.java如下:

packagecom.lei.demo.el; publicclassCustomer{ privateItemitem; privateStringitemName; @Override publicStringtoString(){ return"itemName="+this.itemName+""+"Item.total="+this.item.getTotal(); } //getterandsetter... }

3.SpringEL**——**XML

SpEL格式为#{SpELexpression},xml配置见下。

文件:Spring-EL.xml

<beansxmlns="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"> <beanid="itemBean"class="com.lei.demo.el.Item"> <propertyname="name"value="itemA"/> <propertyname="total"value="10"/> </bean> <beanid="customerBean"class="com.lei.demo.el.Customer"> <propertyname="item"value="#{itemBean}"/> <propertyname="itemName"value="#{itemBean.name}"/> </bean> </beans>

注解:

#{itemBean}——将itemBean注入到customerBean的item属性中。

#{itemBean.name}——将itemBean的name属性,注入到customerBean的属性itemName中。

4.SpringEL**——**Annotation

SpEL的Annotation版本。

注意:要在Annotation中使用SpEL,必须要通过annotation注册组件。如果你在xml中注册了bean和在javaclass中定义了@Value,@Value在运行时将失败。

Item.java如下:

packagecom.lei.demo.el; importorg.springframework.beans.factory.annotation.Value; importorg.springframework.stereotype.Component; @Component("itemBean") publicclassItem{ @Value("itemA")//直接注入String privateStringname; @Value("10")//直接注入integer privateinttotal; //getterandsetter... }

Customer.java如下:

packagecom.lei.demo.el; importorg.springframework.beans.factory.annotation.Value; importorg.springframework.stereotype.Component; @Component("customerBean") publicclassCustomer{ @Value("#{itemBean}") privateItemitem; @Value("#{itemBean.name}") privateStringitemName; //getterandsetter... }

Xml中配置组件自动扫描

<beansxmlns="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-scanbase-package="com.lei.demo.el"/> </beans>

在Annotation模式中,用@Value定义EL。在这种情况下,直接注入一个String和integer值到itemBean中,然后注入itemBean到customerBean中。

5.输出结果

App.java如下:

packagecom.lei.demo.el; importorg.springframework.context.ApplicationContext; importorg.springframework.context.support.ClassPathXmlApplicationContext; publicclassApp{ publicstaticvoidmain(String[]args){ ApplicationContextcontext=newClassPathXmlApplicationContext("Spring-EL.xml"); Customerobj=(Customer)context.getBean("customerBean"); System.out.println(obj); } }

输出结果如下:itemName=itemAitem.total=10

二、SpringELMethodInvocation——SpEL方法调用

SpEL允许开发者用El运行方法函数,并且允许将方法返回值注入到属性中。

1.SpringELMethodInvocation之Annotation

此段落演示用@Value注释,完成SpEL方法调用。

Customer.java如下:

packagecom.lei.demo.el; importorg.springframework.beans.factory.annotation.Value; importorg.springframework.stereotype.Component; @Component("customerBean") publicclassCustomer{ @Value("#{lei.toUpperCase()}") privateStringname; @Value("#{priceBean.getSpecialPrice()}") privatedoubleamount; //getterandsetter...省略 @Override publicStringtoString(){ return"Customer[name="+name+",amount="+amount+"]"; } }

Price.java如下:

packagecom.lei.demo.el; importorg.springframework.stereotype.Component; @Component("priceBean") publicclassPrice{ publicdoublegetSpecialPrice(){ returnnewDouble(99.99); } }

输出结果:Customer[name=LEI,amount=99.99]

上例中,以下语句调用toUpperCase()方法

@Value("#{lei.toUpperCase()}") privateStringname;

上例中,以下语句调用priceBean中的getSpecialPrice()方法

@Value("#{priceBean.getSpecialPrice()}") privatedoubleamount;

2.SpringELMethodInvocation之XML

在XMl中配置如下,效果相同

<beansxmlns="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"> <beanid="customerBean"class="com.leidemo.el.Customer"> <propertyname="name"value="#{lei.toUpperCase()}"/> <propertyname="amount"value="#{priceBean.getSpecialPrice()}"/> </bean> <beanid="priceBean"class="com.lei.demo.el.Price"/> </beans>

三、SpringELOperators——SpEL操作符

SpringEL支持大多数的数学操作符、逻辑操作符、关系操作符。

1.关系操作符

包括:等于(==,eq),不等于(!=,ne),小于(<,lt),,小于等于(<=,le),大于(>,gt),大于等于(>=,ge)

2.逻辑操作符

包括:and,or,andnot(!)

3.数学操作符

包括:加(+),减(-),乘(*),除(/),取模(%),幂指数(^)。

1.SpringELOperators之Annotation

Numer.java如下

packagecom.lei.demo.el; importorg.springframework.beans.factory.annotation.Value; importorg.springframework.stereotype.Component; @Component("numberBean") publicclassNumber{ @Value("999") privateintno; publicintgetNo(){ returnno; } publicvoidsetNo(intno){ this.no=no; } }

Customer.java如下

packagecom.lei.demo.el; importorg.springframework.beans.factory.annotation.Value; importorg.springframework.stereotype.Component; @Component("customerBean") publicclassCustomer{ //Relationaloperators @Value("#{1==1}")//true privatebooleantestEqual; @Value("#{1!=1}")//false privatebooleantestNotEqual; @Value("#{1<1}")//false privatebooleantestLessThan; @Value("#{1<=1}")//true privatebooleantestLessThanOrEqual; @Value("#{1>1}")//false privatebooleantestGreaterThan; @Value("#{1>=1}")//true privatebooleantestGreaterThanOrEqual; //Logicaloperators,numberBean.no==999 @Value("#{numberBean.no==999andnumberBean.no<900}")//false privatebooleantestAnd; @Value("#{numberBean.no==999ornumberBean.no<900}")//true privatebooleantestOr; @Value("#{!(numberBean.no==999)}")//false privatebooleantestNot; //Mathematicaloperators @Value("#{1+1}")//2.0 privatedoubletestAdd; @Value("#{1+@+1}")//1@1 privateStringtestAddString; @Value("#{1-1}")//0.0 privatedoubletestSubtraction; @Value("#{1*1}")//1.0 privatedoubletestMultiplication; @Value("#{10/2}")//5.0 privatedoubletestDivision; @Value("#{10%10}")//0.0 privatedoubletestModulus; @Value("#{2^2}")//4.0 privatedoubletestExponentialPower; @Override publicStringtoString(){ 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+"]"; } }

运行如下代码:

Customerobj=(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 ]

2.SpringELOperators之XML

以下是等同的xml配置。

注意,类似小于号“<”,或者小于等于“<=”,在xml中是不直接支持的,必须用等同的文本表示方法表示,

例如,“<”用“lt”替换;“<=”用“le”替换,等等。

<beansxmlns="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"> <beanid="customerBean"class="com.lei.demo.el.Customer"> <propertyname="testEqual"value="#{1==1}"/> <propertyname="testNotEqual"value="#{1!=1}"/> <propertyname="testLessThan"value="#{1lt1}"/> <propertyname="testLessThanOrEqual"value="#{1le1}"/> <propertyname="testGreaterThan"value="#{1>1}"/> <propertyname="testGreaterThanOrEqual"value="#{1>=1}"/> <propertyname="testAnd"value="#{numberBean.no==999andnumberBean.nolt900}"/> <propertyname="testOr"value="#{numberBean.no==999ornumberBean.nolt900}"/> <propertyname="testNot"value="#{!(numberBean.no==999)}"/> <propertyname="testAdd"value="#{1+1}"/> <propertyname="testAddString"value="#{1+@+1}"/> <propertyname="testSubtraction"value="#{1-1}"/> <propertyname="testMultiplication"value="#{1*1}"/> <propertyname="testDivision"value="#{10/2}"/> <propertyname="testModulus"value="#{10%10}"/> <propertyname="testExponentialPower"value="#{2^2}"/> </bean> <beanid="numberBean"class="com.lei.demo.el.Number"> <propertyname="no"value="999"/> </bean> </beans>

四、SpringEL三目操作符condition?true:false

SpEL支持三目运算符,以此来实现条件语句。

1.Annotation

Item.java如下:

packagecom.lei.demo.el; importorg.springframework.beans.factory.annotation.Value; importorg.springframework.stereotype.Component; @Component("itemBean") publicclassItem{ @Value("99") privateintqtyOnHand; publicintgetQtyOnHand(){ returnqtyOnHand; } publicvoidsetQtyOnHand(intqtyOnHand){ this.qtyOnHand=qtyOnHand; } }

Customer.java如下:

packagecom.lei.demo.el; importorg.springframework.beans.factory.annotation.Value; importorg.springframework.stereotype.Component; @Component("customerBean") publicclassCustomer{ @Value("#{itemBean.qtyOnHand<100?true:false}") privatebooleanwarning; publicbooleanisWarning(){ returnwarning; } publicvoidsetWarning(booleanwarning){ this.warning=warning; } @Override publicStringtoString(){ return"Customer[warning="+warning+"]"; } } 输出:Customer[warning=true]

2.XMl

Xml配置如下,注意:应该用“&lt;”代替小于号“<”

<beansxmlns="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"> <beanid="customerBean"class="com.lei.demo.el.Customer"> <propertyname="warning" value="#{itemBean.qtyOnHand<100?true:false}"/> </bean> <beanid="itemBean"class="com.lei.demo.el.Item"> <propertyname="qtyOnHand"value="99"/> </bean> </beans> 输出:Customer[warning=true]

五、SpringEL操作List、Map集合取值

此段演示SpEL怎样从List、Map集合中取值,简单示例如下:

//getmapwherekey=MapA @Value("#{testBean.map[MapA]}") privateStringmapA; //getfirstvaluefromlist,listis0-based. @Value("#{testBean.list[0]}") privateStringlist;

1.Annotation

首先,创建一个HashMap和ArrayList,并初始化一些值。

Test.java如下:

packagecom.lei.demo.el; importjava.util.ArrayList; importjava.util.HashMap; importjava.util.List; importjava.util.Map; importorg.springframework.stereotype.Component; @Component("testBean") publicclassTest{ privateMap<String,String>map; privateList<String>list; publicTest(){ map=newHashMap<String,String>(); map.put("MapA","ThisisA"); map.put("MapB","ThisisB"); map.put("MapC","ThisisC"); list=newArrayList<String>(); list.add("List0"); list.add("List1"); list.add("List2"); } publicMap<String,String>getMap(){ returnmap; } publicvoidsetMap(Map<String,String>map){ this.map=map; } publicList<String>getList(){ returnlist; } publicvoidsetList(List<String>list){ this.list=list; } }

然后,用SpEL取值,Customer.java如下

packagecom.lei.demo.el; importorg.springframework.beans.factory.annotation.Value; importorg.springframework.stereotype.Component; @Component("customerBean") publicclassCustomer{ @Value("#{testBean.map[MapA]}") privateStringmapA; @Value("#{testBean.list[0]}") privateStringlist; publicStringgetMapA(){ returnmapA; } publicvoidsetMapA(StringmapA){ this.mapA=mapA; } publicStringgetList(){ returnlist; } publicvoidsetList(Stringlist){ this.list=list; } @Override publicStringtoString(){ return"Customer[mapA="+mapA+",list="+list+"]"; } }

调用代码如下:

Customerobj=(Customer)context.getBean("customerBean"); System.out.println(obj); 输出结果:Customer[mapA=ThisisA,list=List0]

2.XML

Xml配置如下:

<beansxmlns="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"> <beanid="customerBean"class="com.lei.demo.el.Customer"> <propertyname="mapA"value="#{testBean.map[MapA]}"/> <propertyname="list"value="#{testBean.list[0]}"/> </bean> <beanid="testBean"class="com.lei.demo.el.Test"/> </beans>

本文内容总结:Spring3系列6-Spring表达式语言(SpringEL),一、第一个SpringEL例子——HelloWorldDemo,二、SpringELMethodInvocation——SpEL方法调用,三、SpringELOperators——SpEL操作符,四、SpringEL三目操作符condition?true:false,五、SpringEL操作List、Map集合取值,一、第一个SpringEL例子——HelloWorldDemo,二、SpringELMethodInvocation——SpEL方法调用,1.SpringELMethodInvocation之Annotation,2.SpringELMethodInvocation之XML,三、SpringELOperators——SpEL操作符,1.SpringELOperators之Annotation,2.SpringELOperators之XML,四、SpringEL三目操作符condition?true:false,1.Annotation,2.XMl,五、SpringEL操作List、Map集合取值,1.Annotation,2.XML,

原文链接:https://www.cnblogs.com/leiOOlei/p/3543222.html