您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

Spring SPEL表达式

Spring SPEL表达式

SpEL 是一种扩展语言,支持在运行时查询和操作对象图的功能。

有很多可用的表达语言,例如JSP EL, OGNL,MVEL和JBoss EL。 SpEL提供了一些其他功能,例如方法调用和字符串模板功能。

SpEL API

SpEL API提供了许多接口和类。它们如下:

Expression接口 SpelExpression类 ExpressionParser接口 SpelExpressionParser类 EvaluationContext接口 StandardEvaluationContext类

Hello SPEL示例

import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
public class Test {
public static void main(String[] args) {
ExpressionParser parser = new SpelExpressionParser();
Expression exp = parser.parseExpression("'Hello SPEL'");
String message = (String) exp.getValue();
System.out.println(message);
//OR
//System.out.println(parser.parseExpression("'Hello SPEL'").getValue());
}
}

其他SPEL示例

让我们看到许多有用的SPEL示例。在这里,我们假设所有示例都已写在main()方法内。

将concat()方法与String配合使用

ExpressionParser parser = new SpelExpressionParser();
Expression exp = parser.parseExpression("'Welcome SPEL'.concat('!')");
String message = (String) exp.getValue();
System.out.println(message);

将字符串转换为字节数组

Expression exp = parser.parseExpression("'Hello World'.bytes");
byte[] bytes = (byte[]) exp.getValue();
for(int i=0;i<bytes.length;i++){
    System.out.print(bytes[i]+" ");
}

将字符串转换为字节后获取长度

Expression exp = parser.parseExpression("'Hello World'.bytes.length");
int length = (Integer) exp.getValue();
System.out.println(length);

将字符串内容转换为大写字母

Expression exp = parser.parseExpression("new String('hello world').toUpperCase()");
String message = exp.getValue(String.class);
System.out.println(message);
//OR
System.out.println(parser.parseExpression("'hello world'.toUpperCase()").getValue());

联系我
置顶