Spring 通过 SpEL 为 bean 赋值
SpEL 字面量的表示
-
整数:
<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"}'/>
-
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、属性和方法
- 引用其他对象:
<property name = "prefix" value="#{prefixGenerator}"/>
- 引用其他对象的属性
<property name = "suffix" value="#{sequenceGenerator2.suffix}"/>
- 调用其他方法
<property name = "suffix" value="#{sequenceGenerator2.suffix}"/>
- 链式操作
<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 支持的运算符号
- 算数运算符:+ - * / % ^
<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}"/>
- 加号还可以用作字符串连接
<constructor-arg value = "#{performer.fistName + ' ' + performer.lastName}"/>
- 比较运算符:< > == <= >= 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>