在Spring EL中,您可以比较两个值以确定它们是否相等,大于或小于另一个值。对于这些比较,下面是Spring EL支持的运算符列表,可以预期的是,它支持与Java编程语言相同的运算符。
Spring Expression Language比较运算符包括:
| 符号 | 文字的 | 描述 |
|---|---|---|
| == | eq | 双等号运算符比较两个值是否相等。 |
| < | lt | 如果一个值小于另一个值,则小于运算符进行比较。 |
| > | gt | 大于运算符,用于比较一个值是否大于另一个值。 |
| <= | le | 小于或等于运算符比较一个值是否小于或等于另一个值。 |
| >= | ge | 大于或等于运算符,用于比较一个值是否大于或等于另一个值。 |
例如,您可以使用双等号运算符,例如以下XML配置:
<property name="empty" value="#{myGlass.volume == 0}"/>这意味着我们将把empty属性设置为布尔值,true或者false将其值设置myGlass.volume为等于0或不等于。在XML文档中使用双等号符号不是问题。但是您会立即理解,不能在XML中使用小于(<)或大于(>)符号,因为这些字符用于定义其自身的XML文档。
为了使其正常工作,我们必须使用这些运算符的文本版本。例如,您将使用lt而不是<符号或gt代替>符号,如上表所示。现在,让我们在spring配置文件中查看一个示例。
<?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="myGlass">
<constructor-arg name="volume" value="5"/>
<constructor-arg name="maxVolume" value="10"/>
<property name="empty" value="#{myGlass.volume == 0}"/>
<property name="halfEmpty" value="#{(myGlass.maxVolume / 2) le myGlass.volume}"/>
</bean>
</beans>在上述配置中,我们有一个名为的bean myGlass。我们使用两个构造函数值实例化它,volume设置为5,maxVolume设置为10。要设置emptyandhalfEmpty属性的值,我们使用双等于和小于等号运算符来检查volumeandmaxVolume属性的值。
进行Spring配置后,让我们创建MyGlassBean和一个应用程序以运行配置文件。Bean只是一个简单的类,具有一些属性以及getter和setter的集合。
package org.nhooo.example.spring.el;
public class MyGlass {
private boolean empty;
private boolean halfEmpty;
private int volume;
private int maxVolume;
public MyGlass() {
}
public MyGlass(int volume, int maxVolume) {
this.volume = volume;
this.maxVolume = maxVolume;
}
public boolean isEmpty() {
return empty;
}
public void setEmpty(boolean empty) {
this.empty = empty;
}
public boolean isHalfEmpty() {
return halfEmpty;
}
public void setHalfEmpty(boolean halfEmpty) {
this.halfEmpty = halfEmpty;
}
public int getVolume() {
return volume;
}
public void setVolume(int volume) {
this.volume = volume;
}
public int getMaxVolume() {
return maxVolume;
}
public void setMaxVolume(int maxVolume) {
this.maxVolume = maxVolume;
}
}要运行上面的spring配置,您可以在SpELCompareValue下面创建类。
package org.nhooo.example.spring.el;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class SpELCompareValue {
public static void main(String[] args) {
ApplicationContext context = new
ClassPathXmlApplicationContext("spel-compare-value.xml");
MyGlass glass = (MyGlass) context.getBean("myGlass");
System.out.println("glass.getVolume() = " + glass.getVolume());
System.out.println("glass.isEmpty() = " + glass.isEmpty());
System.out.println("glass.isHalfEmpty() = " + glass.isHalfEmpty());
}
}当您执行上面的代码时,您将获得以下输出:
glass.getVolume() = 5 glass.isEmpty() = false glass.isHalfEmpty() = true