package app.spel;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.common.TemplateParserContext;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;
public class TestSPEL {
public static void main(String[] args) {
Expression exp;
ExpressionParser parser = new SpelExpressionParser();
exp = parser.parseExpression("'Hello World!'");
System.out.println("1: " + exp.getValue());
exp = parser.parseExpression("2.06");
System.out.println("1: " + exp.getValue(Double.class));
exp = parser.parseExpression("new String[]{'java', 'spring', 'struts2'}");
System.out.println("2: " + ((String[])exp.getValue())[0]);
exp = parser.parseExpression("{'java', 'spring', 'struts2'}");
System.out.println("3: " + exp.getValue());
List<String> list = new ArrayList<String>();
list.add("a");
list.add("b");
list.add("c");
Map<String, String> map = new HashMap<String, String>();
map.put("a", "1");
map.put("b", "2");
EvaluationContext ctx = new StandardEvaluationContext();
ctx.setVariable("mylist", list);
ctx.setVariable("mymap", map);
System.out.println("4: " + parser.parseExpression("#mylist[1]").getValue(ctx));
System.out.println("4: " + parser.parseExpression("#mymap[a]").getValue(ctx));
System.out.println("5: " + parser.parseExpression("'Hello World!'.substring(2, 5)").getValue());
System.out.println("5: " + parser.parseExpression("#mylist.subList(1,2)").getValue(ctx));
System.out.println("6: " + parser.parseExpression("1 + 2").getValue());
System.out.println("7: " + parser.parseExpression("T(java.lang.Math).random()").getValue());
System.out.println("8: " + parser.parseExpression("new String('aaaabbbb')").getValue());
EvaluationContext ctx1 = new StandardEvaluationContext();
ctx1.setVariable("myString", new String("abcd"));
System.out.println("9: " + parser.parseExpression("#myString").getValue(ctx1));
List<String> list1 = new ArrayList<String>();
list1.add("a");
list1.add("bb");
list1.add("ccc");
list1.add("e");
list1.add("fff");
EvaluationContext ctx2 = new StandardEvaluationContext();
ctx2.setVariable("mylist", list1);
System.out.println("12: " + parser.parseExpression("#mylist.?[length() > 1]").getValue(ctx2));
Expression exp1 = parser.parseExpression("My name is #{name}, age is #{age}", new TemplateParserContext());
System.out.println("13: " +
exp1.getValue( new Object(){
public String name = "aa";
public int age = 20;
}));
}
}
1: Hello World!
1: 2.06
2: java
3: [java, spring, struts2]
4: b
4: 1
5: llo
5: [b]
6: 3
7: 0.1892105143597339
8: aaaabbbb
9: abcd
12: [bb, ccc, fff]
13: My name is aa, age is 20