跳到主要内容

变量

DeepSeek V3 中英对照 Variables

你可以通过使用 #variableName 语法在表达式中引用变量。变量是通过在 EvaluationContext 实现中使用 setVariable() 方法来设置的。

备注

变量名必须以字母(如下定义)、下划线或美元符号开头。

变量名必须由以下支持的一种或多种字符类型组成。

  • 字母:任何 java.lang.Character.isLetter(char) 返回 true 的字符

    • 这包括诸如 AZazüñé 等字母,以及来自其他字符集的字母,如中文、日文、西里尔字母等。
  • 数字:09

  • 下划线:_

  • 美元符号:$

提示

EvaluationContext 中设置变量或根上下文对象时,建议将变量或根上下文对象的类型设置为 public

否则,某些涉及非 public 类型的变量或根上下文对象的 SpEL 表达式可能无法评估或编译。

注意

由于变量与函数在评估上下文中共享一个共同的命名空间,因此必须注意确保变量名称和函数名称不会重叠。

以下示例展示了如何使用变量。

Inventor tesla = new Inventor("Nikola Tesla", "Serbian");

EvaluationContext context = SimpleEvaluationContext.forReadWriteDataBinding().build();
context.setVariable("newName", "Mike Tesla");

parser.parseExpression("name = #newName").getValue(context, tesla);
System.out.println(tesla.getName()); // "Mike Tesla"
java

#this#root 变量

#this 变量始终被定义,并指向当前的评估对象(未限定引用的解析对象)。#root 变量也始终被定义,并指向根上下文对象。尽管 #this 可能会随着表达式组件的评估而变化,但 #root 始终指向根对象。

以下示例展示了如何将 #this 变量与集合选择结合使用。

// Create a list of prime integers.
List<Integer> primes = List.of(2, 3, 5, 7, 11, 13, 17);

// Create parser and set variable 'primes' as the list of integers.
ExpressionParser parser = new SpelExpressionParser();
EvaluationContext context = SimpleEvaluationContext.forReadWriteDataBinding().build();
context.setVariable("primes", primes);

// Select all prime numbers > 10 from the list (using selection ?{...}).
String expression = "#primes.?[#this > 10]";

// Evaluates to a list containing [11, 13, 17].
List<Integer> primesGreaterThanTen =
parser.parseExpression(expression).getValue(context, List.class);
java

以下示例展示了如何结合使用 #this#root 变量以及集合投影

// Create parser and evaluation context.
ExpressionParser parser = new SpelExpressionParser();
EvaluationContext context = SimpleEvaluationContext.forReadWriteDataBinding().build();

// Create an inventor to use as the root context object.
Inventor tesla = new Inventor("Nikola Tesla");
tesla.setInventions("Telephone repeater", "Tesla coil transformer");

// Iterate over all inventions of the Inventor referenced as the #root
// object, and generate a list of strings whose contents take the form
// "<inventor's name> invented the <invention>." (using projection !{...}).
String expression = "#root.inventions.![#root.name + ' invented the ' + #this + '.']";

// Evaluates to a list containing:
// "Nikola Tesla invented the Telephone repeater."
// "Nikola Tesla invented the Tesla coil transformer."
List<String> results = parser.parseExpression(expression)
.getValue(context, tesla, List.class);
java