14、spring的EL表达式语言(SpEL)

本文详细介绍了Spring表达式语言(SpEL)的基本概念和应用实例,包括使用SpEL引用bean、调用方法、运算符使用、三目运算、集合操作及正则表达式的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

14、spring的EL表达式语言(SpEL)

Spring EL表达式共有以下几种语法知识:

  1. 使用SpEL引用bean
  2. 使用SpEL调用方法
  3. SpEL的运算符
  4. SpEL的三元运算
  5. SpEL操作集合类型
  6. SpEL的正则表达式

Spring EL表达式有两种实现方式:

  1. 基于xml方式的实现
  2. 基于注解方式的实现

在下面的每一个知识点中,均会以两种形式来介绍


SpEL 的入门例子

第一步:先创建两个实体类
Teacher.java

public class Teacher {
    private Student student;
    private String studentName;
    //setter and getter methods
    //toString methods
}

Student.java

public class Student {
    private String name;
    private String type;
    //setter and getter methods
    //toString methods
}

1、以xml方式实现

bean.xml

    <bean id="Student" class="com.main.autowrite.EL.Student">
        <property name="name" value="jack"/>
        <property name="type" value="student"/>
    </bean>
    <bean id="Teacher" class="com.main.autowrite.EL.Teacher">
        <property name="student" value="#{Student}"/>
        <property name="name" value="#{Student.name}"/>
    </bean>

测试代码和运行结果:

@Test
    public void test(){
        ApplicationContext context = 
                new ClassPathXmlApplicationContext("com/main/autowrite/EL/bean.xml");
        Teacher teacher = (Teacher)context.getBean("Teacher");

        System.out.println(teacher.toString());

    }

这里写图片描述

2、以注解方式实现

修改你的两个实体类如下:
Teacher.java:

@Component("Teacher")
public class Teacher {

    @Value("#{Student}")
    private Student student;

    @Value("#{Student.name}")
    private String studentName;
}

Student.java

@Component("Student")
public class Student {

    @Value("jack")
    private String name;

    @Value("student")
    private String type;
}

然后在bean配置文件中启用组件扫描

<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.main.autowrite.EL" />

</beans>

最后测试运行:

@Test
    public void test(){
        ApplicationContext context = 
                new ClassPathXmlApplicationContext("com/main/autowrite/EL/bean.xml");
        Teacher teacher = (Teacher)context.getBean("Teacher");

        System.out.println(teacher.toString());

    }

这里写图片描述


至此,SpEL的入门例子就完成了。
接下来学习SpEL的其他语法知识。

1、使用SpEL引用bean

以注解的形式引用:

Teacher.java

@Component("Teacher")
public class Teacher {

    @Value("#{Student}")
    private Student student;

    @Value("#{Student.name}")
    private String studentName;
}

Student.java

@Component("Student")
public class Student {

    @Value("jack")
    private String name;

    @Value("student")
    private String type;
}

以XML的形式引用:

<context:component-scan base-package="com.main.autowrite.EL" />
    <bean id="Student" class="...">
        <property name="name" value="jack"/>
    </bean>

    <bean id="Teacher" class="...">
        <property name="Student" value="#{Student}"/>
        <property name="studentName" value="#{Student.name}"/>
    </bean>

2、使用SpEL调用方法

以注解的形式调用:

@Component("Teacher")
public class Teacher {

    @Value("#{Student}")
    private Student student;

    @Value("#{Student.getName()}")
    private String studentName;
}
@Component("Student")
public class Student {

    @Value("jack")
    private String name;

    @Value("student")
    private String type;
}

以XML的形式调用:

<context:component-scan base-package="com.main.autowrite.EL" />
    <bean id="Student" class="...">
        <property name="name" value="jack"/>
    </bean>

    <bean id="Teacher" class="...">
        <property name="Student" value="#{Student}"/>
        <property name="studentName" value="#{Student.getName()}"/>
    </bean>

3、SpEL的运算符

说明:这里说得运算符是指二目运算符

一目:作用预单个运算数,a++,b–等;++和–就是单目运算符
二目:作用于两个运算数,a+b,a*c等。常用的+,-,*,/就是二目运算符
三目:所用于三个运算数,a>b?true:false等。

在注解中使用运算符

@Component("Customer")
public class Customer{

    @Value("#{10==1}") //false
    private boolean Value;

    @Value("#{10-1}")//9
    private int intNumber;

    @Value("#{10/2}")  //5.0
    private double doubleNumber;

    //.......

    //setter and getter methods
}

在XML中使用运算符

<bean id="customerBean" class="...">

      <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="...">
        <property name="no" value="999" />
    </bean>

4、SpEL的三目运算符

注解形式的三目运算符

    @Value("#{10 < 100 ? true : false}")  //true
    private boolean warning;

XML形式的三目运算符

<property name="number" value="#{10 < 100 ? 10 : 100}"/>

5、SpEL的集合

注解形式的集合

@Component("testBean")
public class Test {

    private Map<String, String> map;
    private List<String> list;
}

假设Map和List集合均已经存在初始值

    //引用
    @Value("#{testBean.map['MapA']}")
    private String mapA;

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

XML形式的集合

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

6、SpEL的正则表达式

注解形式的正则表达式:

    // 校验Email的正则表达式
    String emailRegEx = "^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)" +
            "*@[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";

    // true    
    @Value("#{'100' matches '\\d+' }")
    private boolean validDigit;

    // msg:yes this is digit
    @Value("#{ ('100' matches '\\d+') == true ? " +
            "'yes this is digit' : 'No this is not a digit'  }")
    private String msg;

XML形式的正则表达式:

<property name="message"
        value="#{ ('100' matches '\d+') == true ? 'yes this is digit' : 'No this is not a digit'  }" />
      <property name="validateEmail"
        value="#{emailBean.emailAddress matches '^[_A-Za-z0-9-]+(\.[_A-Za-z0-9-]+)*@[A-Za-z0-9]+(\.[A-Za-z0-9]+)*(\.[A-Za-z]{2,})$' }" />
### Spring Expression Language (SpEL) 使用方法及示例 #### SpEL概述 Spring Expression Language(SpEL)是一种强大的表达式语言,允许在运行时查询和操纵对象图。这种语言不仅能够执行逻辑和算术运算,还支持访问属性、调用方法以及处理集合数据结构[^2]。 #### 创建并解析简单的表达式 为了创建一个简单的表达式实例,可以通过`ExpressionParser`接口来实现: ```java import org.springframework.expression.ExpressionParser; import org.springframework.expression.spel.standard.SpelExpressionParser; public class SimpleExpressionExample { public static void main(String[] args) { // 初始化表达式解析器 ExpressionParser parser = new SpelExpressionParser(); // 解析简单数值表达式 String expressionString = "2 + 3"; Integer result = parser.parseExpression(expressionString).getValue(Integer.class); System.out.println("Result of '2 + 3': " + result); // 输出:5 // 访问字符串长度的方法调用 String lengthExp = "'Hello'.length()"; Integer stringLength = parser.parseExpression(lengthExp).getValue(Integer.class); System.out.println("'Hello' Length: " + stringLength); // 输出:5 } } ``` 上述代码展示了如何利用SpEL来进行基础的数学计算以及获取字符串长度的操作[^4]。 #### 对象属性访问与方法调用 除了基本的数据类型外,SpEL同样适用于复杂类型的对象操作。下面的例子说明了怎样通过表达式读取对象字段值或是触发成员函数: ```java // 定义测试类 class Person { private final String name; public Person(String name){ this.name = name; } public String getName(){ return name; } } ... Person person = new Person("John"); ExpressionParser parser = new SpelExpressionParser(); // 获取person对象的名字属性 String nameValue = parser.parseExpression("name").getValue(person, String.class); System.out.println("Name from object property access:" + nameValue); // 调用getName方法 String methodNameCall = parser.parseExpression("getName()").getValue(person, String.class); System.out.println("Name via method call:" + methodNameCall); ``` 这段程序片段揭示了SpEL对于面向对象编程的支持程度——可以直接作用于自定义实体之上完成相应的交互行为[^1]。 #### 集合遍历和支持 当涉及到列表或其他形式的容器时,SpEL也表现出色。这里有一个例子用来展示如何筛选特定条件下的元素: ```java List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); ExpressionParser parser = new SpelExpressionParser(); // 查找偶数项 EvaluationContext context = new StandardEvaluationContext(); context.setVariable("numbers", numbers); String evenNumbersExpr = "#numbers.?[#this % 2 == 0]"; List<Integer> evens = parser.parseExpression(evenNumbersExpr) .getValue(context, List.class); System.out.println("Even Numbers are:" + evens.toString()); ``` 此部分强调了SpEL处理数组或集合的能力,特别是针对过滤需求的应用场景[^3]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值