8.Spring EL与ExpressionParser

Spring EL与ExpressionParser

文章目录

介绍

Spring表达式语言(SpEL)支持多种功能,并且可以测试这个特殊的"ExpressionParser"接口的表达式功能。

下面是两个代码片段,展示了使用 Spring EL 的基本用法

使用SpEL来计算评估文字字符串表达式

java 复制代码
ExpressionParser parser = new SpelExpressionParser();
Expression exp = parser.parseExpression("'put spel expression here'");
String msg = exp.getValue(String.class); 

使用SpEL来计算评估 bean 属性 -- "item.name"

java 复制代码
Item item = new Item("yiibai", 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

java 复制代码
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("yiibai", 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 == 'yiibai'
		Expression exp5 = parser.parseExpression("name == 'yiibai'");
		boolean msg5 = exp5.getValue(itemContext, Boolean.class);
		System.out.println(msg5);
		
	}
}
java 复制代码
public class Item {

	private String name;

	private int qty;

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

	//...
}

输出结果

复制代码
Hello World
相关推荐
高明珠1 小时前
麒麟 V10 SP1 排查实录:ttyS5 每 10 秒莫名收到一批报文,元凶是 eGTouchD
后端
卷无止境1 小时前
Python FFI 技术深度解析:ctypes、cffi 与 pybind11 的性能差异与实践挑战
后端·python
ServBay2 小时前
AI Gateway 是什么?为什么每个平台都在做
后端·aigc·ai编程
SamDeepThinking2 小时前
Vibe Coding最重要的是Spec
后端·程序员·ai编程
掘金_答案2 小时前
上线那天,一个 ConcurrentHashMap 差点送走我的 AI 客服——3 天排查 JVM 血泪史
java·后端·架构
妙码生花2 小时前
从 PHP 到 AI + Golang,程序员自救转型手记(三十三):权限规则管理器
后端·go·gin
MindUp2 小时前
企业网盘权限模型解析:多层级访问控制与审计能力选型指南
java·linux·运维
Kim_wang2 小时前
agent项目部署流程
人工智能·后端
NG4773 小时前
【软件设计与体系结构】-策略设计模式
java·设计模式·软件工程
程序员天天困3 小时前
优雅记录操作日志:从注解到 SpEL 的全链路实践与开源方案对比
java·后端