java xml 表达式语言_Spring学习(十三)-----Spring 表达式语言(Spring EL)

本文详细介绍了Spring Expression Language(SpEL),一种功能强大的表达式语言,用于在运行时查询和操作对象图。通过示例展示了如何在XML和Annotation中使用SpEL进行属性注入、方法调用、操作符运用、三目运算符以及从List和Map中取值。SpEL支持关系、逻辑和数学操作符,使得在Spring应用中动态表达式变得简单高效。
摘要由CSDN通过智能技术生成

概要

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

一、第一个Spring EL例子—— HelloWorld Demo

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

1.Spring El的依赖包

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

文件:pom.xml

org.springframework

spring-core

3.2.4.RELEASE

org.springframework

spring-context

3.2.4.RELEASE

2.Spring Bean

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

Item.java如下:

packagecom.lei.demo.el;

public classItem {

privateString name;

private inttotal;

//getter and setter...

}

Customer.java如下:

packagecom.lei.demo.el;

public classCustomer {

privateItem item;

privateString itemName;

@Override

publicString toString() {

return "itemName=" +this.itemName+" "+"Item.total="+this.item.getTotal();

}

//getter and setter...

}

3.Spring EL——XML

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

文件:Spring-EL.xml

注解:

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如下:

packagecom.lei.demo.el;

importorg.springframework.beans.factory.annotation.Value;

importorg.springframework.stereotype.Component;

@Component("itemBean")

public classItem {

@Value("itemA")//直接注入String

privateString name;

@Value("10")//直接注入integer

private inttotal;

//getter and setter...

}

Customer.java如下:

packagecom.lei.demo.el;

importorg.springframework.beans.factory.annotation.Value;

importorg.springframework.stereotype.Component;

@Component("customerBean")

public classCustomer {

@Value("#{itemBean}")

privateItem item;

@Value("#{itemBean.name}")

privateString itemName;

//getter and setter...

}

Xml中配置组件自动扫描

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

5.输出结果

App.java如下:

packagecom.lei.demo.el;

importorg.springframework.context.ApplicationContext;

importorg.springframework.context.support.ClassPathXmlApplicationContext;

public classApp {

public static voidmain(String[] args) {

ApplicationContext context = new ClassPathXmlApplicationContext("Spring-EL.xml");

Customer obj = (Customer) context.getBean("customerBean");

System.out.println(obj);

}

}

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

二、Spring EL Method Invocation——SpEL 方法调用

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

1.Spring EL Method Invocation之Annotation

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

Customer.java如下:

packagecom.lei.demo.el;

importorg.springframework.beans.factory.annotation.Value;

importorg.springframework.stereotype.Component;

@Component("customerBean")

public classCustomer {

@Value("#{'lei'.toUpperCase()}")

privateString name;

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

private doubleamount;

//getter and setter...省略

@Override

publicString toString() {

return "Customer [name=" + name + ", amount=" + amount + "]";

}

}

Price.java如下:

packagecom.lei.demo.el;

importorg.springframework.stereotype.Component;

@Component("priceBean")

public classPrice {

public doublegetSpecialPrice() {

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;

2. Spring EL Method Invocation之XML

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

三、Spring EL Operators——SpEL 操作符

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

1.关系操作符

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

2.逻辑操作符

包括:and,or,and not(!)

3.数学操作符

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

1. Spring EL Operators之Annotation

Numer.java如下

packagecom.lei.demo.el;

importorg.springframework.beans.factory.annotation.Value;

importorg.springframework.stereotype.Component;

@Component("numberBean")

public classNumber {

@Value("999")

private intno;

public intgetNo() {

returnno;

}

public void setNo(intno) {

this.no =no;

}

}

Customer.java如下

packagecom.lei.demo.el;

importorg.springframework.beans.factory.annotation.Value;

importorg.springframework.stereotype.Component;

@Component("customerBean")

public classCustomer {

//Relational operators

@Value("#{1 == 1}") //true

private booleantestEqual;

@Value("#{1 != 1}") //false

private booleantestNotEqual;

@Value("#{1 < 1}") //false

private booleantestLessThan;

@Value("#{1 <= 1}") //true

private booleantestLessThanOrEqual;

@Value("#{1 > 1}") //false

private booleantestGreaterThan;

@Value("#{1 >= 1}") //true

private booleantestGreaterThanOrEqual;

//Logical operators , numberBean.no == 999

@Value("#{numberBean.no == 999 and numberBean.no < 900}") //false

private booleantestAnd;

@Value("#{numberBean.no == 999 or numberBean.no < 900}") //true

private booleantestOr;

@Value("#{!(numberBean.no == 999)}") //false

private booleantestNot;

//Mathematical operators

@Value("#{1 + 1}") //2.0

private doubletestAdd;

@Value("#{'1' + '@' + '1'}") //1@1

privateString testAddString;

@Value("#{1 - 1}") //0.0

private doubletestSubtraction;

@Value("#{1 * 1}") //1.0

private doubletestMultiplication;

@Value("#{10 / 2}") //5.0

private doubletestDivision;

@Value("#{10 % 10}") //0.0

private doubletestModulus ;

@Value("#{2 ^ 2}") //4.0

private doubletestExponentialPower;

@Override

publicString 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]

2.      Spring EL Operators之XML

以下是等同的xml配置。

注意,类似小于号“

例如,“

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

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

1.      Annotation

Item.java如下:

packagecom.lei.demo.el;

importorg.springframework.beans.factory.annotation.Value;

importorg.springframework.stereotype.Component;

@Component("itemBean")

public classItem {

@Value("99")

private intqtyOnHand;

public intgetQtyOnHand() {

returnqtyOnHand;

}

public void setQtyOnHand(intqtyOnHand) {

this.qtyOnHand =qtyOnHand;

}

}

Customer.java如下:

packagecom.lei.demo.el;

importorg.springframework.beans.factory.annotation.Value;

importorg.springframework.stereotype.Component;

@Component("customerBean")

public classCustomer {

@Value("#{itemBean.qtyOnHand < 100 ? true : false}")

private booleanwarning;

public booleanisWarning() {

returnwarning;

}

public void setWarning(booleanwarning) {

this.warning =warning;

}

@Override

publicString toString() {

return "Customer [warning=" + warning + "]";

}

}

输出:Customer [warning=true]

2. XMl

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

输出:Customer [warning=true]

五、Spring EL 操作List、Map集合取值

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

//get map where key = 'MapA'

@Value("#{testBean.map['MapA']}")

privateString mapA;

//get first value from list, list is 0-based.

@Value("#{testBean.list[0]}")

private String list;

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")

public classTest {

private Mapmap;

private Listlist;

publicTest() {

map = new HashMap();

map.put("MapA", "This is A");

map.put("MapB", "This is B");

map.put("MapC", "This is C");

list = new ArrayList();

list.add("List0");

list.add("List1");

list.add("List2");

}

public MapgetMap() {

returnmap;

}

public void setMap(Mapmap) {

this.map =map;

}

public ListgetList() {

returnlist;

}

public void setList(Listlist) {

this.list =list;

}

}

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

packagecom.lei.demo.el;

importorg.springframework.beans.factory.annotation.Value;

importorg.springframework.stereotype.Component;

@Component("customerBean")

public classCustomer {

@Value("#{testBean.map['MapA']}")

privateString mapA;

@Value("#{testBean.list[0]}")

privateString list;

publicString getMapA() {

returnmapA;

}

public voidsetMapA(String mapA) {

this.mapA =mapA;

}

publicString getList() {

returnlist;

}

public voidsetList(String list) {

this.list =list;

}

@Override

publicString toString() {

return "Customer [mapA=" + mapA + ", list=" + list + "]";

}

}

调用代码如下:

Customer obj = (Customer) context.getBean("customerBean");

System.out.println(obj);

输出结果:Customer [mapA=This is A, list=List0]

2.      XML

Xml配置如下:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值