首页 > 代码库 > Spring文档苦读【7】【Spring Expression Language(SpEL)】

Spring文档苦读【7】【Spring Expression Language(SpEL)】

简介

Spring Expression Language(Spring表达式语言),用来解析java语言中的相关并获得反馈。

下面就摘录官方示例来简单描述一下。也作一下标记,方便以后查阅。

示例

示例1

1 ExpressionParser parser = new SpelExpressionParser();
2 Expression exp = parser.parseExpression("‘Hello World‘");
3 String message = (String) exp.getValue();

变量message的值为:Hello World

示例2

1 ExpressionParser parser = new SpelExpressionParser();
2 Expression exp = parser.parseExpression("‘Hello World‘.concat(‘!‘)");
3 String message = (String) exp.getValue();

变量message的值为:Hello World!

示例3

1 ExpressionParser parser = new SpelExpressionParser();
2 
3 // invokes ‘getBytes()‘
4 Expression exp = parser.parseExpression("‘Hello World‘.bytes");
5 byte[] bytes = (byte[]) exp.getValue();

示例4

1 ExpressionParser parser = new SpelExpressionParser();
2 
3 // invokes ‘getBytes().length‘
4 Expression exp = parser.parseExpression("‘Hello World‘.bytes.length");
5 int length = (Integer) exp.getValue();

示例5

1 ExpressionParser parser = new SpelExpressionParser();
2 Expression exp = parser.parseExpression("new String(‘hello world‘).toUpperCase()");
3 String message = exp.getValue(String.class);

示例6

 1 // Create and set a calendar
 2 GregorianCalendar c = new GregorianCalendar();
 3 c.set(1856, 7, 9);
 4 
 5 // The constructor arguments are name, birthday, and nationality.
 6 Inventor tesla = new Inventor("Nikola Tesla", c.getTime(), "Serbian");
 7 
 8 ExpressionParser parser = new SpelExpressionParser();
 9 Expression exp = parser.parseExpression("name");
10 
11 EvaluationContext context = new StandardEvaluationContext(tesla);
12 String name = (String) exp.getValue(context);

获取对象tesla的属性name的值。

示例7

 1 / Create and set a calendar
 2 GregorianCalendar c = new GregorianCalendar();
 3 c.set(1856, 7, 9);
 4 
 5 // The constructor arguments are name, birthday, and nationality.
 6 Inventor tesla = new Inventor("Nikola Tesla", c.getTime(), "Serbian");
 7 
 8 ExpressionParser parser = new SpelExpressionParser();
 9 Expression exp = parser.parseExpression("name == ‘Nikola Tesla‘");
10 boolean result = exp.getValue(context, Boolean.class); // evaluates to true

变量result为判断对象tesla的属性name是否和字符串‘Nikola Tesla‘相同。

 

Spring文档苦读【7】【Spring Expression Language(SpEL)】