Spring 表达式语言(简称SpEL):是一个支持运行时查询和操作对象图的强大的表达式语言。语法类似于 EL:SpEL 使用 #{…} 作为定界符,所有在大框号中的字符都将被认为是 SpEL
SpEL 为 bean 的属性进行动态赋值提供了便利
SpEL 为 bean 的属性进行动态赋值提供了便利
通过 SpEL 可以实现:通过 bean 的 id 对 bean 进行引用;调用方法以及引用对象中的属性;计算表达式的值;正则表达式的匹配
案例:三个bean,Person,Car,Adress,get set方法请自行产生
Adress类的属性:
private String city;
private String street;
Car类的属性:
private String brand;
private double price;
//轮胎周长
private double tyrePerimeter;
Person类的属性:
private String name;
private Car car;
//引用address bean的city属性
private String city;
//根据car的价格确定info ,>300000金领 否则白领
private String info;
applicationContext_spel.xml文件配置如下:
<?xml version="1.0" encoding="UTF-8"?>
<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.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">
<bean id="address" class="com.cgc.spring.beans.spel.Address">
<!-- 使用spel为属性赋一个字面值 -->
<property name="city" value="#{'BeiJing'}"></property>
<property name="street" value="WuDaoKou"></property>
</bean>
<bean id="car" class="com.cgc.spring.beans.spel.Car">
<property name="brand" value="Audi"></property>
<property name="price" value="500000"></property>
<!-- 使用spel引用类的静态属性 -->
<property name="tyrePerimeter" value="#{T(java.lang.Math).PI*80}"></property>
</bean>
<bean id="person" class="com.cgc.spring.beans.spel.Person">
<!-- 在spel中使用其他的Bean -->
<property name="car" value="#{car}"></property>
<!-- 使用其他bean的属性 -->
<property name="city" value="#{address.city}"></property>
<!-- 在spel中使用运算符 -->
<property name="info" value="#{car.price>300000? '金领' :'白领'}"></property>
</bean>
</beans>