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
广告

© . All rights reserved.