Spring Expression Language 简明教程

Spring SpEL - Elvis Operator

SpEL 表达式支持 Elvis 运算符,它是一种三元运算符的简写形式。

// Using ternary operator
String result = name != null ? name: "unknown";

// Using Elvis Operator
result = name?:"unknown";

以下示例显示了各种使用案例。

Example

让我们更新在 Spring SpEL - Create Project 章节创建的项目。我们添加/更新了以下文件:

  1. Employee.java − Employee class.

  2. MainApp.java - 要运行和测试的主应用。

以下 Employee.java 文件的内容:

package com.tutorialspoint;

public class Employee {
   private String name;

   public String getName() {
      return name;
   }
   public void setName(String name) {
      this.name = name;
   }
}

以下 MainApp.java 文件的内容:

package com.tutorialspoint;

import java.text.ParseException;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;

public class MainApp {
   public static void main(String[] args) throws ParseException {
      ExpressionParser parser = new SpelExpressionParser();
      Employee employee = new Employee();
      EvaluationContext employeeContext = new StandardEvaluationContext(employee);

      // Evaluates to "unknown"
      String result = parser.parseExpression("name?:'unknown'").getValue(employeeContext, String.class);
      System.out.println(result);

      employee.setName("Mahesh");

      // Evaluates to "Mahesh"
      result = parser.parseExpression("name?:'unknown'").getValue(employeeContext, String.class);
      System.out.println(result);
   }
}

Output

unknown
Mahesh