Spring-Bean配置-SpEL

Spring 表達式語言(簡稱SpEL):是一個支持運行時查詢和操作對象圖的強大的表達式語言。語法類似於 EL:SpEL 使用 #{…} 作爲定界符,所有在大框號中的字符都將被認爲是 SpEL
SpEL 爲 bean 的屬性進行動態賦值提供了便利

通過 SpEL 可以實現:通過 bean 的 id 對 bean 進行引用;調用方法以及引用對象中的屬性;計算表達式的值;正則表達式的匹配

案例:三個bean,Person,Car,Adress,get set方法請自行產生

Adress類的屬性:

   private String city;
   private String street;
Car類的屬性:

    private String brand;
    private double price;
    //輪胎周長
    private double tyrePerimeter;
Person類的屬性:

    private String name;
    private Car car;
    //引用address bean的city屬性
    private String city;
    //根據car的價格確定info ,>300000金領  否則白領
    private String info;
applicationContext_spel.xml文件配置如下:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">
	
	<bean id="address" class="com.cgc.spring.beans.spel.Address">
	<!-- 使用spel爲屬性賦一個字面值 -->
		<property name="city" value="#{'BeiJing'}"></property>
		<property name="street" value="WuDaoKou"></property>
	</bean>
	
	<bean id="car" class="com.cgc.spring.beans.spel.Car">
		<property name="brand" value="Audi"></property>
		<property name="price" value="500000"></property>
		<!-- 使用spel引用類的靜態屬性 -->
		<property name="tyrePerimeter" value="#{T(java.lang.Math).PI*80}"></property>
	</bean>
	
	<bean id="person" class="com.cgc.spring.beans.spel.Person">
	    <!-- 在spel中使用其他的Bean -->
		<property name="car" value="#{car}"></property>
		<!-- 使用其他bean的屬性 -->
		<property name="city" value="#{address.city}"></property>
		<!-- 在spel中使用運算符 -->
		<property name="info" value="#{car.price>300000? '金領' :'白領'}"></property>
	</bean>
		
</beans>

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章