简介

  • Spring表达式语言,简称SpEL,是一个支持运行时查询和操作对象图的强大表达式语言。
  • 语法:使用#{…}作为定界符,为bean的属性进行动态赋值。

    代码示例

    <?xml version="1.0" encoding="UTF-8"?>
    <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.xsd">
    
        <bean id="car" class="com.itdjx.spring.spel.Car">
            <!--直接value="玛莎拉蒂"也可以-->
            <property name="brand" value="#{'玛莎拉蒂'}"></property>
            <!-- 或者
            <property name="brand" value='#{"玛莎拉蒂"}'></property>
            -->
            <!--直接value="32000.78"也可以-->
            <property name="price" value="#{32000.78}"></property>
            <!--调用静态方法的属性-->
            <property name="perimeter" value="#{T(java.lang.Math).PI * 75.8f}"></property> 
        </bean>
    
        <bean id="person" class="com.itdjx.spring.spel.Person">
            <!--调用对象的方法或属性,判断表达式#{true}/#{false},marriage为Boolean型-->
            <property name="marriage" value="#{car.price > 400000 and age > 30}"></property>
            <!--引用bean,之前为:<property name="car" ref="car"></property>-->
            <property name="car" value="#{car}"></property>
            <property name="socialStatus" value="#{car.price > 30000 ? '金领' : '白领'}"></property>
            <property name="address" value="#{address.province + '省' + address.city + '市' + address.area + '区'}"/>
        </bean>
    
        <bean id="address" class="com.itdjx.spring.spel.Address">
            <property name="province" value="#{'辽宁'}"/>
            <property name="city" value="#{'大连'}"/>
            <property name="area" value="#{'沙河口'}"/>
        </bean>
    
    </beans>
    
  • SpEL

    • 整数:#{8}
    • 小数:#{8.8}
    • 科学计数法:#{1e4}
    • String:使用单或双引号作为字符串的定界符
    • Boolean:#{true}
    • 引用对象:#{car}
    • 引用对象属性:#{car.brand}
    • 调用对象方法:#{car.toString()},还可以链式操作
    • 调用静态方法静态属性、静态方法:#{T(java.lang.Math).PI},#{T(java.lang.Math).random()}使用T()调用类作用域的方法和常量
    • 支持算术运算符:+,-,*,/,%,^(加号还可以用作字符串连接)
    • 比较运算符:/gt , ==/eq , >=/ge , <=/le
    • 逻辑运算符:and , or , not , |
    • 三目运算符:? :
    • 正则表达式:#{admin.email matches ‘[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}’}

  • 避免抛出空指针异常:加个?,它会确保在左边项为null时不调用后面方法

    <property name="song" value="#{songSelector.selectSong()?.toUpperCase()}" />