在此示例中,您将学习如何在Spring Expression Language中使用三元运算符。如果条件为三元运算符,则将Spring EL评估为一个值,如果条件为true,则评估为另一个值false。三元运算符是使用?:符号编写的,就像您在Java中所做的一样。测试条件放在?符号的左侧,而评估表达式放在:符号之间。
作为示例,让我们看看如何在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="book1">
<property name="type" value="Novel"/>
</bean>
<bean id="book2">
<property name="type" value="#{book1.type != null ? book1.type : 'Novel'}"/>
</bean>
<bean id="book3">
<property name="type" value="#{book1.type ?: 'Novel'}"/>
</bean>
</beans>在配置中,您将看到有两种方法可以使用操作符。在book2bean上,我们使用操作符的常用用法。我们检查book1.type是否不等于null,如果这是true,那么我们将book1.type作为值,否则我们只将类型赋给'Novel'。
第一个示例中有一些重复项。如您所见,我们在该行代码中两次调用boo1.type。实际上,Spring EL版本可以为您提供较短的版本。您可以像在book3Bean中一样使用三元运算符,而不是像之前那样做。这样我们就可以输入了book1.type ?: 'Novel'。这将给我们相同的结果。
创建配置后,您还将需要Book该类。所以这是Book类的定义。
package org.nhooo.example.spring.el;
public class Book {
private String type;
public Book() {
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}最后,让我们创建一个类来运行spring配置。此类基本上只是加载spring配置文件spel-ternary.xml并获取一些bean,这些Bookbean来自应用程序上下文并打印出其type属性的值。
package org.nhooo.example.spring.el;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class SpELTernaryOperatorExample {
public static void main(String[] args) {
ApplicationContext context =
new ClassPathXmlApplicationContext("spel-ternary.xml");
Book book1 = (Book) context.getBean("book1");
Book book2 = (Book) context.getBean("book2");
Book book3 = (Book) context.getBean("book3");
System.out.println("book1.getType() = " + book1.getType());
System.out.println("book2.getType() = " + book2.getType());
System.out.println("book3.getType() = " + book3.getType());
}
}这是您将获得的执行输出。
book1.getType() = Novel book2.getType() = Novel book3.getType() = Novel