spring3表达式语言(SpEL)

时间:2023-03-10 00:04:36
spring3表达式语言(SpEL)

使用SpEl进行表达式操作,基本操作如下:

<!--第一步,构建解析 -->
ExpressionParser parser = new SpelExpressionParser(); <!--第二步,使用表达式进行解析-->
Expression exp = parser.parseExpression( "('hello').concat(#end)"); <!--第三步,使用上下文设值(可省)-->
StandardEvaluationContext sec = new StandardEvaluationContext();
sec.setVariable("end", "!"); <!--第四步,获取结果-->
<!--没有第三步时-->
exp.getValue();
<!--有第三步时-->
exp.getValue(sec);
  

  

▲基础特性

——SpEL使用#{…}作为定界符,所有在大框号中的字符都将被认为是SpEL.

——1、 字面量的表示

<property name="count" value="#{5}"/>
<property name="frequency" value="#{89.7}"/>
<property name="capacity" value="#{1e4}"/>
<property name="name" value="#{'Chuck'}"/>
<property name='name' value='#{"Chuck"}'/>
<property name="enabled" value="#{false}"/>

——2、 引用Bean,属性和方法

1>引用其他对象

<bean id=”saxophone” value=”com.xxx.xxx.Xxx”/>
<bean ..>
.
<property name="instrument" value="#{saxophone}"/>
.
<bean/>

  通过id:“saxophone”将对象注入到instrument属性中,这与下面的配置是一样的:

<property name="instrument" ref="saxophone"/>

   2> 引用其他对象的属性

<bean id="carl"
class="com.springinaction.springidol.Instrumentalist">
<property name="song" value="#{kenny.song}" />
</bean>

  ▲SpEL对集合的支持

<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"/>
<bean class="com.habuma.spel.cities.City"
p:name="Odessa" p:state="TX" p:population="90943"/>
<bean class="com.habuma.spel.cities.City"
p:name="El Paso" p:state="TX" p:population="613190"/>
<bean class="com.habuma.spel.cities.City"
p:name="Jal" p:state="NM" p:population="1996"/>
<bean class="com.habuma.spel.cities.City"
p:name="Las Cruces" p:state="NM" p:population="91865"/>
</util:list>

——1、 获取Collection中的某个对象

〇通过下标访问,如下:

<property name="chosenCity" value="#{cities[2]}"/>

——2、获取Collection中的子集-通过条件筛选(注意新对象是一个新的Collection)

 <!--筛选子集(.?[])-->
<property name="bigCities" value="#{cities.?[population gt 100000]}"/> <!--获取第一个(.^[])-->
<property name="aBigCity" value="#{cities.^[population gt 100000]}"/> <--获取最后一个(.$[])-->
<property name="aBigCity" value="#{cities.$[population gt 100000]}"/>

——3、集合的投影(.![])

<!-- 如果想获得所有城市的名称组成的列表,可用如下操作,将返回"Chicago", "Atlanta", "Dallas" -->
<property name="cityNames" value="#{cities.![name]}"/> <!-- 将返回"Chicago, IL", "Atlanta, GA", and "Dallas, TX".-->
<property name="cityNames" value="#{cities.![name + ', ' + state]}"/>