測試 Spring EL與ExpressionParser

Spring運算式語言(SpEL)支持多種功能,並且可以測試這個特殊的“ExpressionParser”介面的運算式功能。
下麵是兩個代碼片段,展示了使用 Spring EL 的基本用法。
使用SpEL來計算評估文字字串運算式。
ExpressionParser parser = new SpelExpressionParser();
Expression exp = parser.parseExpression("'put spel expression here'");
String msg = exp.getValue(String.class); 

使用SpEL來計算評估 bean 屬性 – “item.name”.

Item item = new Item("zaixian", 100);
StandardEvaluationContext itemContext = new StandardEvaluationContext(item);

//display the value of item.name property
Expression exp = parser.parseExpression("name");
String msg = exp.getValue(itemContext, String.class);
舉幾個例子來測試使用SpEL。這些代碼和注釋應該是自我探索。
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 App {
	public static void main(String[] args) {

		ExpressionParser parser = new SpelExpressionParser();

		//literal expressions
		Expression exp = parser.parseExpression("'Hello World'");
		String msg1 = exp.getValue(String.class);
		System.out.println(msg1);

		//method invocation
		Expression exp2 = parser.parseExpression("'Hello World'.length()");
		int msg2 = (Integer) exp2.getValue();
		System.out.println(msg2);

		//Mathematical operators
		Expression exp3 = parser.parseExpression("100 * 2");
		int msg3 = (Integer) exp3.getValue();
		System.out.println(msg3);

		//create an item object
		Item item = new Item("zaixian", 100);
		//test EL with item object
		StandardEvaluationContext itemContext = new StandardEvaluationContext(item);

		//display the value of item.name property
		Expression exp4 = parser.parseExpression("name");
		String msg4 = exp4.getValue(itemContext, String.class);
		System.out.println(msg4);

		//test if item.name == 'zaixian'
		Expression exp5 = parser.parseExpression("name == 'zaixian'");
		boolean msg5 = exp5.getValue(itemContext, Boolean.class);
		System.out.println(msg5);

	}
}
public class Item {

	private String name;

	private int qty;

	public Item(String name, int qty) {
		super();
		this.name = name;
		this.qty = qty;
	}

	//...
}

輸出結果

Hello World
11
200
zaixian
true



本文展示了Spring運算式解析器的一些基本用法,訪問官方Spring表達文檔,使用SpEL的例子。


上一篇: Spring EL正則運算式實例 下一篇: Spring自動掃描組件