spring学习(十三)-----spring表达式语言(springel)

     2022-03-24     458

关键词:

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

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

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

三、      Spring EL Operators——SpEL 操作符

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

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

 

 

一、      第一个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.lei.demo.el;

public class Item {

    private String name;
    private int total;
    
    //getter and setter...
}
技术分享

 

Customer.java如下:

技术分享
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——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.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注入到customerBeanitem属性中。

2. #{itemBean.name}——将itemBeanname属性,注入到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

 

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

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

1.      Spring EL Method Invocation之Annotation

此段落演示用@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;

 

 

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.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 Operators——SpEL 操作符

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

  1.关系操作符

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

  2.逻辑操作符

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

  3.数学操作符

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

1.      Spring EL Operators之Annotation

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‘}") //[email protected]
    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, 
    [email protected], 
    testSubtraction=0.0, 
    testMultiplication=1.0, 
    testDivision=5.0, 
    testModulus=0.0, 
    testExponentialPower=4.0
]
技术分享

 

 

2.      Spring EL Operators之XML

以下是等同的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>
技术分享

 

 

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

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

1.      Annotation

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]

 

2.      XMl

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

技术分享
<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 &lt; 100 ? true : false}" />
    </bean>
 
    <bean id="itemBean" class="com.lei.demo.el.Item">
        <property name="qtyOnHand" value="99" />
    </bean>
 
</beans>
技术分享

 

 

输出:Customer [warning=true]

 

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

此段演示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;
技术分享

 

 

1.      Annotation

首先,创建一个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]

 

2.      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.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>
技术分享

 

spring(十三)--spring泛型处理(代码片段)

Java5类型接口-java.lang.reflect.TypeJava泛型反射APISpring泛型类型辅助类核心API-org.springframework.core.GenericTypeResolver1.处理类型相关(Type)相关方法resolveReturnType:获取方法返回值的TyperesolveType:2.处理泛型参数类型(ParameterizedType)相关方法r 查看详情

spring(十三)--spring泛型处理(代码片段)

Java5类型接口-java.lang.reflect.TypeJava泛型反射APISpring泛型类型辅助类核心API-org.springframework.core.GenericTypeResolver1.处理类型相关(Type)相关方法resolveReturnType:获取方法返回值的TyperesolveType:2.处理泛型参数类型(ParameterizedType)相关方法r 查看详情

spring源码分析(二十三)beanfactory的后处理

摘要:本文结合《Spring源码深度解析》来分析Spring5.0.6版本的源代码。若有描述错误之处,欢迎指正。 目录一、激活注册的BeanFactoryPostProcessor1.BeanFactoryPostProcessor的典型应用:PropertyPlaceholderConfigurer2.使用自定义BeanFactoryPostProces... 查看详情

spring使用spring表达式(springel)(代码片段)

  Spring还提供了更灵活的注入方式,那就是Spring表达式,实际上SpringEL远比以上注入方式强大,我们需要学习它。SpringEL拥有很多功能。  使用Bean的id来引用Bean。  •调用指定对象的方法和访问对象的属性。  •进... 查看详情

基于spring+springmvc+mybatis开发书评网(十三)后台管理之wangeditor图片上传(代码片段)

...易用、开源免费wangeditor学习网址1、pom.xml引入依赖<!--SpringMVC文件上传底层依赖--><dependency>& 查看详情

spring源码分析(十三)缓存中获取单例bean

摘要:本文结合《Spring源码深度解析》来分析Spring5.0.6版本的源代码。若有描述错误之处,欢迎指正。 介绍过FactoryBean的用法后,我们就可以了解bean加载的过程了。前面已经提到过,单例在Spring的同一个容器内只会被创建一... 查看详情

thymeleaf学习

...式@{...}:URL表达式~{...}:片段表达式变量表达式将Thymeleaf与Spring集成-在上下文变量(在Spring行话中也称为Springjargon)上执行OGNL表达式长这样:${session.user.name}他们可以作为属性的值,像这样:<spanth:text=" 查看详情

akka学习教程(十三)akka分布式(代码片段)

...布式实战akka学习教程(十三)akka分布式akka学习教程(十二)Spring与Akka的集成akka学习教程(十一)akka持久化akka学习教程(十)agentakka学习教程(九)STM软件事务内存akka学习教程(八)Actor中的Future-询问模式akka学习教程(七)内置状态转换Procedurea... 查看详情

spring学习5:基于注解实现spring的aop

目录spring学习5:基于注解实现spring的aop一、基于注解+xml实现1.1在配置文件中开启spring对注解aop的支持1.2把通知类用注解配置到容器中,并用注解声明为切面1.3定义切入点表达式1.4定义通知二、基于纯注解实现三、多个aop的执行顺... 查看详情

高质量spring实战学习笔记,腾讯内部学习spring首推

Spring框架已经成为Java开发人员的必备知识,而且Spring3引入了强大的新特性,例如SpEL、Spring表达式语言、loC容器的新注解以及用户急需的对REST的支持。无论你是刚刚接触Spring还是被Spring3.0的新特性所吸引,这份笔记... 查看详情

jmeter学习(二十三)关联

话说LoadRunner有的一些功能,比如:参数化、检查点、集合点、关联,Jmeter也都有这些功能,只是功能可能稍弱一些,今天就关联来讲解一下。JMeter的关联方法有两种:后置处理器-正则表达式提取器与XPathExtractor。 一、正则... 查看详情

jmeter学习(二十三)关联

话说LoadRunner有的一些功能,比如:参数化、检查点、集合点、关联,Jmeter也都有这些功能,只是功能可能稍弱一些,今天就关联来讲解一下。JMeter的关联方法有两种:后置处理器-正则表达式提取器与XPathExtractor。 一、正则... 查看详情

spring基础(十三):jdbctemplate的批操作(代码片段)

文章目录JDBCTemplate的批操作一、实体类二、DeptService三、DeptDao四、测试JDBCTemplate的批操作一次连接,操作表格里的多条数据,就是批量操作。案例操作批量增加批量修改批量删除一、实体类packagecom.lanson.pojo;importlombok.AllAr... 查看详情

spring十三种模式之--装饰器模式

解释:装饰器模式(DecoratorPattern)允许向一个现有的对象添加新的功能,同时又不改变其结构。这种类型的设计模式属于结构型模式,它是作为现有的类的一个包装。这种模式创建了一个装饰类,用来包装原有的类,并在保持... 查看详情

前方高能预警!阿里大佬出品“spring实战学习笔记”震撼来袭

Spring框架已经成为Java开发人员的必备知识,而且Spring3引入了强大的新特性,例如SpEL、Spring表达式语言、loC容器的新注解以及用户急需的对REST的支持。无论你是刚刚接触Spring还是被Spring3.0的新特性所吸引,这份笔记... 查看详情

前方高能预警!阿里大佬出品“spring实战学习笔记”震撼来袭!(代码片段)

Spring框架已经成为Java开发人员的必备知识,而且Spring3引入了强大的新特性,例如SpEL、Spring表达式语言、loC容器的新注解以及用户急需的对REST的支持。无论你是刚刚接触Spring还是被Spring3.0的新特性所吸引,这份笔记... 查看详情

spring框架学习——spring的体系结构详解

1、Spring体系结构简介Spring框架至今已集成了20多个模块,这些模块分布在以下模块中:核心容器(CoreContainer)数据访问/集成(DataAccess/Integration)层Web层AOP(AspectOrientedProgramming)模块植入(Instrumentation)模块消息传输(Messaging... 查看详情

spring学习8-ssh需要的jar包

struts2commons-logging-1.0.4.jar主要用于日志处理freemarker-2.3.8.jar模板相关操作需要包ognl-2.6.11.jarognl表达示所需包,xwork-2.0.7.jarxwork核心包struts2-core-2.0.14.jarstruts2核心包struts2-spring-plugin-2.0.14.jarstruts2整合spring所需 查看详情