使用Spring表达式语言进行装配
SpEL特性
- 使用bean的ID来引用bean;
- 调用方法和访问对象的属性
- 对值进行算术、关系和逻辑运算
- 正则表达式匹配
- 集合操作SpEL 表达式要放到 “#{…}”之中
样例
#{T(System).currentTimeMillis()} //T()表达式会将java.lang.System 视为Java中对应的类型,因此可以调用其static方法
#{sgtPeppers.artist} //引用其他bean或其他bean的属性
#(systemProperties['disc.title'])//通过systemProperties对象引用系统属性
public BlankDisc(@Value("#{systemProperties['disc.title']}") String title,@Value("#{systemProperties['disc.title']}) String artist){
this.title = title;
this.artist = artist;
}
<bean id="" class=""
c:_title="#{systemProperties['disc.title']}"
c:_artist="#{systemProperties['disc.artist']}" />
-----------------------------------------
SpEL也可以表示字面值
#{3.14159}
#{9.87E4}
#{'hello'}
#{false}
--------------------------------------------
引用bean、属性和方法
用bean ID 引用bean
#{sgtPeppers}
bean的属性
#{sgtPeppers.artist}
调用bean的方法
#{artistSelector.selectArtist()}
d对于有返回值的方法还可以继续调用返回值的方法
#{artistSelector.selectArtist().toUpperCase()}
在表达式中使用类型
如果要在SpEL中访问类作用域的方法和常量的话,要依赖T()
如
T(java.lang.Math).PI
T(java.lang.Math).random()
#{2* T(java.lang.Math).PI * circle.radius}
SpEL运算符
运算符类型 | 运算符 |
---|---|
算术运算 | +、 -、 *、 % 、 ^ |
比较运算 | ,>, <, ==, <=, >=, lt, gt, eq, le, ge |
逻辑运算 | and or not |
条件运算 | ?: (ternary) ?: (Elvis) |
正则表达式 | matches |
#{ counter.total == 100}
#{counter.total eq 100}
#{ scoreboard.score > 100 ? "Win":"lose"}
#{disc.title ?: 'Rattle and Hum'}//判断title是否为null 是返回Rattle ANDhum
计算正则表达式
#{admin.email matches '正则表达式'} //匹配成功则返回true
计算集合
#{jukebox.songs[4].title} // []用来从集合或数组中安索引取元素
#{'This is a test'[3]} 表示s
.^[] 和 .$[] 用来在集合中查询第一个和最后一个匹配项
#{jukesongs.songs.^[artist(属性名) eq 'Aero']}
.?[] 过滤集合
#{jukebox.songs.?[artist eq 'AERO']}
.![] 投影运算,选择特定属性放到另一个集合张
#{jukebox.songs.![title]} 所有title属性 放到新的String集合