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
相关推荐
SimonKing14 分钟前
给Deepseek Harness装上插件市场,从此插件无忧
java·后端·程序员
艾莉丝努力练剑23 分钟前
【AI大模型接入SDK】C++的SessionManager 线程安全
java·开发语言·前端·c++·人工智能·学习·安全
aiotto资源分享1 小时前
Python 写 JSON 文件,程序中途退出会留下什么?
java·python·json·jsondecodeerror
利威尔xu1 小时前
Go Mutex 饥饿模式:正常模式等待者饿死,1ms 阈值自动切换崩溃
开发语言·后端·面试·golang·并发编程
一条Go1 小时前
边缘 Agent:为什么是它连出来,而不是平台连进去
后端·架构·github
RuoyiOffice1 小时前
SpringBoot3+Vue3 采购到付款:ERP、WMS与财务如何按同一来源协同
java·spring boot·架构·vue
huangfuyk2 小时前
前端融入/转后端避坑指南:AI 时代的安全边界、数据防线与实战细节
后端·ai编程
文丑颜不良啊2 小时前
LeetCode3261~3280题目解析
java·leetcode
代码不停2 小时前
Spring 原理
java·spring
掘金者阿豪2 小时前
GitLab 服务器疑似遭入侵:从 502 故障到 Root 权限异常的完整排查复盘
后端