Spring 表达式语言SpEL 简单介绍和应用

使用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集合
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值