ExpressionParserでSpring elをテストする
Spring式言語(SpEL)は多くの機能をサポートしており、この特別な「ExpressionParser」インターフェースを使用してこれらの式機能をテストできます。
ここに2つのコードスニペットがあり、Spring ELの基本的な使用方法を示しています。
リテラル文字列式を評価するSpEL。
ExpressionParser parser = new SpelExpressionParser();
Expression exp = parser.parseExpression("'put spel expression here'");
String msg = exp.getValue(String.class);
Beanプロパティを評価するSpEL –「item.name」。
Item item = new Item("example", 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("example", 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 == 'example'
Expression exp5 = parser.parseExpression("name == 'example'");
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 example true
Note
この記事は、Spring式パーサーのいくつかの基本的な使用法を示しています。このofficial Spring expression documentationにアクセスして、数百の有用なSpELの例を確認してください。
ソースコードをダウンロード
ダウンロード–Spring3-EL-Parser-Example.zip(6 KB)