spring boot 最佳實踐(五)--SpEL
阿新 • • 發佈:2019-02-03
SpEL 擁有許多特性,包括:
表示式語言支援以下功能
- 文字表達式
- 引用Bean屬性和方法
- 類表示式
- 訪問 properties, arrays, lists, maps
- 布林和關係運算符
- 正則表示式
- 方法呼叫
- 關係運算符
- 引數
- 呼叫建構函式
- 構造Array
- 內嵌lists
- 內嵌maps
- 三元運算子
- 變數
- 使用者定義的函式
- 集合投影
- 集合篩選
- 模板表示式
基本語法
#{ } 標記會提示Spring 這個標記裡的內容是SpEL表示式。
#{rootBean.nestBean.propertiy} “.”操作符表示屬性或方法引用,支援層次呼叫
#{aList[0] } 陣列和列表使用方括號獲得內容
#{aMap[key] } maps使用方括號獲得內容
#{rootBean?.propertiy} 此處"?"是安全導航運算子器,避免空指標異常
#{condition ? trueValue : falseValue} 三元運算子(IF-THEN-ELSE)
#{valueA?:defaultValue} Elvis操作符,當valueA為空時賦值defaultValue
使用SpEL裝配Bean
spring支援通過執行期執行的表示式將值裝配到Bean的屬性或構造器引數中。spring boot預設使用基於註解的配置,@Value註解可以在域,方法和方法/構造器引數中使用來指定一個預設值。
//import org.springframework.beans.factory.annotation.Value;
@Value("#{xxxx}")
private String attribute1;
目前在配置經常使用@Value(“${xxxx}”)
其中$表示獲取配置引數
1. 文字表達式
@Value("#{24}") //整型
@Value("#{'中國'}") //String
//裡面有個單引號,如果去掉會報錯。String 型別的字面值可以使用單引號或雙引號作為字串的界定符。
@Value("my name is #{'david'}") //與非SpEL 表示式的值混用
@Value("#{120.4}") //浮點型數字
@Value ("#{true}") //布林值
2. 引用Bean屬性和方法
@Value("#{beanId}") //使用Bean ID 將一個Bean 裝配到另一個Bean 的屬性中
@Value("#{beanId.attribute}") //使用Bean 的引用來獲取Bean 的屬性
@Value("#{beanId.getSomenthing()}") //呼叫引用Bean的方法
3. 類表示式
SpEL使用T() 運算子呼叫類作用域的方法和常量。
@Value("#{T(java.lang.Math).PI}")
@Value("#{T(java.lang.Math).random()}")
@Value("#{T(java.lang.Math).random() * 100.0 }")
4. 訪問 properties
spel有兩個可用的預定義變數 “systemProperties” 和 “systemEnvironment”。
- systemProperties — java.util.Properties物件,從執行環境中檢索屬性。相當於java程式碼System.getProperty(arg0)
- systemEnvironment — java.util.Properties物件,檢索執行環境的具體屬性。相當於java程式碼System.getenv(arg0)
@Value("#{ systemProperties['user.region'] }")
@Value("#{ systemEnvironment['profile'] }")
使用Spring的表達介面求值
下面的程式碼使用SpEL API來解析文字字串表示式 Hello World.
ExpressionParser parser = new SpelExpressionParser();
Expression exp = parser.parseExpression("'Hello World'");
String message = (String) exp.getValue(); // "hello world"
exp = parser.parseExpression("'Hello World'.concat('!')");
message = (String) exp.getValue();// "Hello World!"
模板資料繫結
#使用者評分
SCORE=auditInfo.auditInfo==null?"":auditInfo.auditInfo["score"]
#渠道號
CHANNEL_NO=auditInfo.artificialAuditInfo.channelNo
#渠道名稱
CHANNEL_NAME=auditInfo.artificialAuditInfo.channelName
Map<String, Expression> expressions = new HashMap<>();
propertis.keySet().forEach(
k -> expressions.put(k, parser.parseExpression(propertis.getString(k))));
Map<String, Object> target = new HashMap<>();
expressions.keySet().forEach(key ->
target.put(key, expressions.get(key).getValue(origin))});
參考