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進行引用
等同於
引用另外一個id爲saxophone的bean作爲instrument的值
對其他bean中某個屬性的引用
- <bean id=“carl” class=“com.springinaction.Instrumentalist”>
- <property name=“song” value=“#{kenny.song}”/>
- </bean>
對其他bean中某個方法的引用
調用id爲songSelector的bean的selectSong()方法,使用其返回值作爲song的值,這也帶來一個問如果selectSong()方法返回一個null,那麼會拋出一個空指針異常
<property name=”song” value=”#{songSelector.selectSong()?.toUpperCase()}”/>,表達式(?.)可以確保在selectSong()返回不爲空的情況下調用toUpperCase()方法,如果返回空那麼不繼續調用後面的方法
對類進行引用
如果某個類是外部類,而不是spring中定義的bean,那麼怎麼進行引用呢?
使用表達式T(),例如:
spel計算表達式的值
spel表達式支持各種各樣的運算符,我們可以可以運用這些運算符來計算表達式的值
使用spel從集合中篩選元素:
使用spring的util namespace中的元素<util:list>定義一個集合
- <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>
<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文件
基於某個屬性對集合中的元素進行過濾
<property name=”bigCitis” value=”#{cities.?[population gt 10000]}”/>選中人口大一10000的cities中的元素作爲bigCitis的值,同操作符(.?[])類似, 操作符(.^[]選取滿足要求的第一個元素, .$[]選取滿足要求的最後一個)
選中已有集合中元素的某一個或幾個屬性作爲新的集合
<property name=”cityNames” value=”#{cities.![name + “, ” + state]}”/>