Spring spel variable example

StandardEvaluationContext:

The StandardEvaluationContext is a class which implements EvaluationContext interface. It uses a reflection mechanism to resolve properties or methods. We can set a variable using the method setVariable on the StandardEvaluationContext. We can use this variable in the expression by using the syntax #variableName.

Example:

MulitplicationTest.java

public class MulitplicationTest {
	int num1;
	int num2;
 
	public int getNum1() {
		return num1;
	}
	public void setNum1(int num1) {
		this.num1 = num1;
	}
	public int getNum2() {
		return num2;
	}
	public void setNum2(int num2) {
		this.num2 = num2;
	}
 
	public int multiplication(){
		return num1*num2;
	}
 
}

MulitplicationTest.java

import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;
 
/**
 * Spring SPEL variable example.
 * @author w3schools
 */
public class Test {
 public static void main(String args[]){	
	//Create MulitplicationTest object.
	MulitplicationTest mulitplicationTest=new MulitplicationTest();
 
	//Create StandardEvaluationContext object 
	//with MulitplicationTest object.  
	StandardEvaluationContext context=
			new StandardEvaluationContext(mulitplicationTest);  
 
	//Create a parser with default settings.
	ExpressionParser parser = new SpelExpressionParser(); 
 
	//Set variables values.
	parser.parseExpression("num1").setValue(context,"10");  
	parser.parseExpression("num2").setValue(context,"20"); 
 
	//Calculate result.
	System.out.println(mulitplicationTest.multiplication());  
 }
}

Output:

200

 
Download this example.