简介
SPEL 是一种强大的表达式语言。在Spring产品组合中,它是表达式计算的基础。它支持在运行时查询和操作对象图,它可以与基于XML和基于注解的Spring配置还有bean定义一起使用。
说点人话:
SPEL表达式可集成数据库或者配置表实现简单的动态业务实现
SPEL表达式可用于日记的动态字段记录
Git地址
https://gitee.com/wqrzsy/lp-demo/tree/master/lp-springboot-spel
更多demo请关注
springboot demo实战项目
java 脑洞
java 面试宝典
开源工具
项目分析
- maven 引入
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-expression</artifactId>
<version>5.1.8.RELEASE</version>
</dependency>
- 获取spring ioc 里面的bean,并调用bean方法
Map<String, Object> dataMap = new HashMap<>();
dataMap.put("test", new Test());
String result = spelExcetor.doneInSpringContext(dataMap, "@testController.test()");
- 获取指定属性名的参数,并调用方法
Map<String, Object> dataMap = new HashMap<>();
dataMap.put("test", new Test());
String result = spelExcetor.doneInSpringContext(dataMap, "#test.getName()");
4.SpEL运算符
运算符类型 运算符
算术比较 +、-、*、/、%、^
比较运算 <、>、==、<=、>=、lt、gt、rq、le、ge
逻辑运算 and、or、not、|、!
条件运算 ?: (ternary)、?:(Elvis)
正则表达式 matches
#{2*T(java.lang.Math).PI * circle.radius} //圆周长计算
#{T(java.lang.Math).PI * circle.radius^2} //圆面积计算
#{disc.title + 'by' + disc.artist} // + 是连接符
#{counter.total == 100} #{counter.total eq 100} //判断是否一致,返回true和false
#{counter.total > 100 ? "Winner" : "Loser"} //三元表达式
#{disc.title ?: 'Rattle'} //Elvis,如果是null的话结果则为Rattle
#{admin.email matches '[a-zA-Z0-9._%+-]+@[a-zA-Z0-9._-]+\\.com'} //正则表达式
#{!(3 > 2)} // 返回的是false
5.其他,基本和在java写逻辑没啥区别了
Map<String, Object> dataMap = new HashMap<>();
dataMap.put("test", new Test());
String result = spelExcetor.doneInSpringContext(dataMap, "99 > 100 ? true : false");
PS:
用spel做业务功能,需要用流式的数据处理思想,举个栗子
Map<String, Object> dataMap = new HashMap<>();
dataMap.put("test", new Test());
String result = spelExcetor.doneInSpringContext(dataMap, "#test.getName().concat(\" world\").substring(0, 4)");
4. 测试
http://localhost:8080/swagger-ui.html
demo项目导入
参考: https://www.jianshu.com/p/cd0275a2f5fb
公众号
五分钟了解前沿技术,大数据,微服务,区域链,提供java前沿技术干货,独立游戏制作技术分享
扫描二维码关注公众号,回复:
9115409 查看本文章
如果这篇文章对你有帮助请给个star