在SpEL中,我们可以将值存储在变量中,然后在方法中使用变量并调用方法。要处理变量,我们需要使用 StandardEvaluationContext 类。
Calculation.java
public class Calculation { private int number; public int getNumber() { return number; } public void setNumber(int number) { this.number = number; } public int cube(){ return number*number*number; } }
Test.java
import org.springframework.expression.ExpressionParser; import org.springframework.expression.spel.standard.SpelExpressionParser; import org.springframework.expression.spel.support.StandardEvaluationContext; public class Test { public static void main(String[] args) { Calculation calculation=new Calculation(); StandardEvaluationContext context=new StandardEvaluationContext(calculation); ExpressionParser parser = new SpelExpressionParser(); parser.parseExpression("number").setValue(context,"5"); System.out.println(calculation.cube()); } }