且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

强大的Spring的EL表达式

更新时间:2022-05-28 08:36:24

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

这个例子将展示如何利用SpEL注入String、Integer、Bean到属性中。
1) Spring El的依赖包

首先在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)Spring Bean

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

package com.spring.hello;
public class Item {
    private String name;
    private int total;
    //getter and setter...
}

Customer.java如下:

package com.spring.hello;
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——XML

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.spring.hello.Item">
        <property name="name" value="itemA" />
        <property name="total" value="10" />
    </bean>

    <bean id="customerBean" class="com.spring.hello.Customer">
        <property name="item" value="#{itemBean}" />
        <property name="itemName" value="#{itemBean.name}" />
    </bean>

</beans>

注解:

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

4) Spring EL——Annotation
SpEL的Annotation版本。
注意:要在Annotation中使用SpEL,必须要通过annotation注册组件。如果你在xml中注册了bean和在java class中定义了@Value,@Value在运行时将失败。
Annotation版本就相当于直接使用Java代码来配置,XML憎恨者会对这样的特性有着极大的兴趣。
Item.java如下:

package com.spring.hello;
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.spring.hello;
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.spring.hello" />

</beans>

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

App.java如下:

package com.spring.hello;

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

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

SpEL允许开发者用El运行方法函数,并且允许将方法返回值注入到属性中。
1)Spring EL Method Invocation之Annotation版本

此段落演示用@Value注释,完成SpEL方法调用。
Customer.java如下:

package com.spring.hello;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component("customerBean")
public class Customer {

    @Value("#{'jinkai'.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.spring.hello;
import org.springframework.stereotype.Component;
@Component("priceBean")
public class Price {

    public double getSpecialPrice() {
        return new Double(99.99);
    }

}

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

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

@Value(“#{‘jinkai’.toUpperCase()}”)
private String name;

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

@Value(“#{priceBean.getSpecialPrice()}”)
private double amount;

2) Spring EL Method Invocation之XML版本
在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.spring.hello.Customer">
        <property name="name" value="#{'shiyanlou'.toUpperCase()}" />
        <property name="amount" value="#{priceBean.getSpecialPrice()}" />
    </bean>

    <bean id="priceBean" class="com.spring.hello.Price" />

</beans>

三、Spring EL Operators——SpEL 操作符

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

  • 关系操作符
    包括:等于 (==, eq),不等于 (!=, ne),小于 (<, lt),,小于等于(<= , le),大于(>, gt),大于等于 (>=, ge) (注意:Xml配置如下,注意:应该用“&lt;”代替小于号“<”,“<=”用“le”替换 )
  • 逻辑操作符
    包括:and,or,and not(!)
  • 数学操作符
    包括:加 (+),减 (-),乘 (*),除 (/),取模 (%),幂指数 码如下:

Spring EL 三目操作符condition?true:false
比如:

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

xml版本

 <property name="warning" value="#{itemBean.qtyOnHand &lt; 100 ? true : false}" />

Spring EL 支持从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;

xml版本

  <property name="mapA" value="#{testBean.map['MapA']}" />
  <property name="list" value="#{testBean.list[0]}" />