簡介
SPEL 是一種強大的表達式語言。在Spring產(chǎn)品組合中,它是表達式計算的基礎(chǔ)。它支持在運行時查詢和操作對象圖,它可以與基于XML和基于注解的Spring配置還有bean定義一起使用。
說點人話:
SPEL表達式可集成數(shù)據(jù)庫或者配置表實現(xiàn)簡單的動態(tài)業(yè)務(wù)實現(xiàn)
SPEL表達式可用于日記的動態(tài)字段記錄
Git地址
https://gitee.com/wqrzsy/lp-demo/tree/master/lp-springboot-spel
更多demo請關(guān)注
springboot demo實戰(zhàn)項目
java 腦洞
java 面試寶典
開源工具
項目分析
- maven 引入
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-expression</artifactId>
<version>5.1.8.RELEASE</version>
</dependency>
- 獲取spring ioc 里面的bean,并調(diào)用bean方法
Map<String, Object> dataMap = new HashMap<>();
dataMap.put("test", new Test());
String result = spelExcetor.doneInSpringContext(dataMap, "@testController.test()");
- 獲取指定屬性名的參數(shù),并調(diào)用方法
Map<String, Object> dataMap = new HashMap<>();
dataMap.put("test", new Test());
String result = spelExcetor.doneInSpringContext(dataMap, "#test.getName()");
4.SpEL運算符
運算符類型 運算符
算術(shù)比較 +、-、*、/、%、^
比較運算 <、>、==、<=、>=、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的話結(jié)果則為Rattle
#{admin.email matches '[a-zA-Z0-9._%+-]+@[a-zA-Z0-9._-]+\\.com'} //正則表達式
#{!(3 > 2)} // 返回的是false
5.其他,基本和在java寫邏輯沒啥區(qū)別了
Map<String, Object> dataMap = new HashMap<>();
dataMap.put("test", new Test());
String result = spelExcetor.doneInSpringContext(dataMap, "99 > 100 ? true : false");
PS:
用spel做業(yè)務(wù)功能,需要用流式的數(shù)據(jù)處理思想,舉個栗子
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項目導(dǎo)入
參考: http://www.itdecent.cn/p/cd0275a2f5fb
如果這篇文章對你有幫助請給個star

image.png