Spring SpEL - 評估上下文



EvaluationContext 是 Spring SpEL 的一個介面,它有助於在上下文中執行表示式字串。在表示式求值期間遇到引用時,會在該上下文中解析這些引用。

語法

以下是如何建立 EvaluationContext 並使用其物件獲取值的示例。

ExpressionParser parser = new SpelExpressionParser();
Expression exp = parser.parseExpression("'name'");
EvaluationContext context = new StandardEvaluationContext(employee);
String name = (String) exp.getValue();

它應該列印如下結果

Mahesh

這裡的結果是 employee 物件的 name 欄位的值,即 Mahesh。StandardEvaluationContext 類指定了評估表示式的物件。一旦建立了上下文物件,StandardEvaluationContext 就無法更改。它快取狀態並允許快速執行表示式求值。以下示例展示了各種用例。

示例

以下示例顯示了一個名為 MainApp 的類。

讓我們更新在Spring SpEL - 建立專案章節中建立的專案。我們新增以下檔案:

  • Employee.java - 員工類。

  • MainApp.java - 執行和測試的主要應用程式。

以下是 Employee.java 檔案的內容:

package com.tutorialspoint;

public class Employee {
   private String id;
   private String name;
   public String getId() {
      return id;
   }
   public void setId(String id) {
      this.id = id;
   }
   public String getName() {
      return name;
   }
   public void setName(String name) {
      this.name = name;
   }
}

以下是 MainApp.java 檔案的內容:

package com.tutorialspoint;

import org.springframework.expression.EvaluationContext;
import org.springframework.expression.Expression;
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) {
      Employee employee = new Employee();
      employee.setId(1);
      employee.setName("Mahesh");

      ExpressionParser parser = new SpelExpressionParser();
      EvaluationContext context = new StandardEvaluationContext(employee);
      Expression exp = parser.parseExpression("name");
      
      // evaluate object using context
      String name = (String) exp.getValue(context);
      System.out.println(name);

      Employee employee1 = new Employee();
      employee1.setId(2);
      employee1.setName("Rita");

      // evaluate object directly
      name = (String) exp.getValue(employee1);
      System.out.println(name);
      exp = parser.parseExpression("id > 1");
      
      // evaluate object using context
      boolean result = exp.getValue(context, Boolean.class);
      System.out.println(result);  // evaluates to false

      result = exp.getValue(employee1, Boolean.class);
      System.out.println(result);  // evaluates to true
   }
}

輸出

Mahesh
Rita
false
true
廣告