Spring 通过 SpEL 为 bean 赋值

2020-01-24  本文已影响0人  桑鱼nicoo

SpEL 字面量的表示

  1. 整数:<property name = "count" value="#{5}"/>

  2. 小数:<property name = "frequency" value="#{89.7}"/>

  3. 科学计数法:<property name = "capacity" value="#{1e4}"/>

  4. 字符串:<property name = "name" value="#{'Chuck'}"/><property name = 'name' value='#{"Chuck"}'/>

  5. Boolean: <property name = "enabled" value="#{false}"/>

 <bean id="address" class="com.sangyu.test02.Address">
        <property name="city" value="#{'Beijing'}"></property>
        <property name="street" value="Wudaokou"></property>
</bean>

SpEL 引用 Bean、属性和方法

  1. 引用其他对象:

<property name = "prefix" value="#{prefixGenerator}"/>

  1. 引用其他对象的属性

<property name = "suffix" value="#{sequenceGenerator2.suffix}"/>

  1. 调用其他方法

<property name = "suffix" value="#{sequenceGenerator2.suffix}"/>

  1. 链式操作

<property name = "suffix" value="#{sequenceGenerator2.toString().toUpperCase()}"/>

// 引用类的静态属性
<bean id="address" class="com.sangyu.test02.Address">
    <property name="city" value="#{'Beijing'}"></property>
    <property name="street" value="Wudaokou"></property>
</bean>

<bean id="car" class="com.sangyu.test02.Car">
    <property name="brand" value="Audi"></property>
    <property name="price" value="#{T(java.lang.Math).PI * 80}"></property>
</bean>

SpEL 支持的运算符号

  1. 算数运算符:+ - * / % ^

<property name = "adjustAmout" value="#{counter.total + 42}"/>

<property name = "adjustAmout" value="#{counter.total - 42}"/>

<property name = "adjustAmout" value="#{2 * T(java.lang.Math).PI * circle.radius}"/>

<property name = "adjustAmout" value="#{counter.total / counter.count}"/>

<property name = "adjustAmout" value="#{counter.total % counter.count}"/>

<property name = "adjustAmout" value="#{T(java.lang.Math).PI * circle.radius ^ 2}"/>

  1. 加号还可以用作字符串连接

<constructor-arg value = "#{performer.fistName + ' ' + performer.lastName}"/>

  1. 比较运算符:< > == <= >= lt gt eg le ge
    <property name = "equal" value="#{counter.total == 100}"/>
    <property name = "hasCapacity" value="#{counter.total le 1000000}"/>
<bean id="address" class="com.sangyu.test02.Address">
    <property name="city" value="#{'Beijing'}"></property>
    <property name="street" value="Wudaokou"></property>
</bean>

<bean id="car" class="com.sangyu.test02.Car">
    <property name="brand" value="Audi"></property>
    <property name="price" value="#{T(java.lang.Math).PI * 80}"></property>
</bean>

<bean id="person" class="com.sangyu.test02.Person">
    <property name="car" value="#{car}"></property>  <!-- 引用其他bean-->
    <property name="city" value="address.city"></property> <!-- 引用其他bean的属性-->
    <property name="info" value="#{car.price > 30000 ? '金领' : '白领'}"></property> <!-- 使用运算符-->
    <property name="name" value="Tom"></property>
</bean>
上一篇下一篇

猜你喜欢

热点阅读