spring in action第三版讀書筆記
spring3.0引入了spring expression language(spel)語言,通過spel我們可以實現
1.通過bean的id對bean進行引用
2.調用方法以及引用對象中的屬性
3.計算表達式的值
4.正則表達式的匹配
5.集合的操作
spel最終的目標是得到表達式計算之后的值,這些表達式可能是列舉的一些值,引用對象的某些屬性,或者是類中的某些常量,復雜的spel表達式通常都是由一些簡單的元素構成的。最簡單的僅僅是得到一些給出元素的值,例如:
<property name="count" value="the value is #{5}"/>。這種情況貌似很傻,根本就不需要用到spel,但是復雜的表達式都是由簡單的構成的
對其他bean的引用
通過spel我們也可以對context中其他的bean進行引用
1
|
< property name = "instrument" value = "#{saxophone}" /> |
等同于
1
|
< property name = "instrument" ref = "saxophone" /> |
引用另外一個id為saxophone的bean作為instrument的值
對其他bean中某個屬性的引用
1
2
3
|
< bean id = "carl" class = "com.springinaction.Instrumentalist" > < property name = "song" value = "#{kenny.song}" /> </ bean > |
取id為kenny的bean的song字段的作為song的value
對其他bean中某個方法的引用
1
|
< property name = "song" value = "#{songSelector.selectSong().toUpperCase()}" /> |
調用id為songSelector的bean的selectSong()方法,使用其返回值作為song的值,這也帶來一個問如果selectSong()方法返回一個null,那么會拋出一個空指針異常
<property name="song" value="#{songSelector.selectSong()?.toUpperCase()}"/>,表達式(?.)可以確保在selectSong()返回不為空的情況下調用toUpperCase()方法,如果返回空那么不繼續調用后面的方法
對類進行引用
如果某個類是外部類,而不是spring中定義的bean,那么怎么進行引用呢?
使用表達式T(),例如:
1
|
< property name = "randomNumber" value = "#{T(java.lang.Math).random()}" /> |
spel計算表達式的值
spel表達式支持各種各樣的運算符,我們可以可以運用這些運算符來計算表達式的值
使用spel從集合中篩選元素:
使用spring的util namespace中的元素<util:list>定義一個集合
1
2
3
4
5
6
7
8
9
10
|
< util:list id = "cities" > < bean class = "com.habuma.spel.cities.City" p:name = "Chicago" p:state = "IL" p:population = "2853114" /> < bean class = "com.habuma.spel.cities.City" p:name = "Atlanta" p:state = "GA" p:population = "537958" /> < bean class = "com.habuma.spel.cities.City" p:name = "Dallas" p:state = "TX" p:population = "1279910" /> < bean class = "com.habuma.spel.cities.City" p:name = "Houston" p:state = "TX" p:population = "2242193" /> </ util:list > |
使用spel對集合進行篩選
<property name="chosenCity" value="#{cities[2]}"/>,
[]操作符也可以對Map進行篩選,假設citis是一個Map類型<property name="chosenCity" value="#{cities["keyName"]}"/>
[]對Properties類型進行操作
<util:properties id="settings"
location="classpath:settings.properties"/>使用<util:properties>標簽讀取一個properties文件
1
|
< property name = "accessToken" value = "#{settings['twitter.accessToken']}" /> |
1
2
3
4
|
基于某個屬性對集合中的元素進行過濾 < property name = "bigCitis" value = "#{cities.?[population gt 10000]}" />選中人口大一10000的cities中的元素作為bigCitis的值,同操作符(.?[])類似, 操作符(.^[]選取滿足要求的第一個元素, .$[]選取滿足要求的最后一個) 選中已有集合中元素的某一個或幾個屬性作為新的集合 < property name = "cityNames" value = "#{cities.![name + " , " + state]}"/> |
總結
以上就是本文關于Spring spel表達式使用方法示例的全部內容,希望對大家有所幫助。
原文鏈接:http://blog.csdn.net/yangnianbing110/article/details/7614521