Spring EL與OGNL和JSF EL相似,計算評估或在bean創建時執行。此外,所有的Spring運算式都可以通過XML或注解。
在本教學中,我們將學習如何使用Spring運算式語言(SpEL),注入字串,整數,Bean到屬性,無論是在XML和注釋。
1. Spring Beans
兩個簡單Bean,後來利用 SpEL 注入值到屬性,在 XML 和 注釋。
package com.zaixian.core;
public class Customer {
private Item item;
private String itemName;
}
package com.zaixian.core;
public class Item {
private String name;
private int qty;
}
3. Spring EL以XML形式
使用 SpEL關閉的#{ SpEL expression }括弧,請參閱XML bean定義檔下麵的例子。
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="itemBean" class="com.zaixian.core.Item">
<property name="name" value="itemA" />
<property name="qty" value="10" />
</bean>
<bean id="customerBean" class="com.zaixian.core.Customer">
<property name="item" value="#{itemBean}" />
<property name="itemName" value="#{itemBean.name}" />
</bean>
</beans>
- #{itemBean} – 注入“itemBean”到“customerBean”Bean 的“item”屬性。
- #{itemBean.name} – 注入“itemBean”的“name”屬性到 “customerBean" bean的"itemname”屬性。
4. Spring EL以注解形式
請參閱等效版本注釋模式。
注
要在注解使用使用SpEL,必須通過注解註冊您的組件。如果註冊bean在XML和Java類中定義@Value,該@Value將無法執行。
package com.zaixian.core;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component("customerBean")
public class Customer {
@Value("#{itemBean}")
private Item item;
@Value("#{itemBean.name}")
private String itemName;
//...
}
package com.zaixian.core;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component("itemBean")
public class Item {
@Value("itemA") //inject String directly
private String name;
@Value("10") //inject interger directly
private int qty;
public String getName() {
return name;
}
//...
}
啟用自動組件掃描。
<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-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <context:component-scan base-package="com.zaixian.core" /> </beans>
在注解模式下,可以使用@Value定義Spring EL。在這種情況下,一個String和Integer值直接注入到“itemBean”,之後又注入“itemBean”到“customerBean”屬性。
5. 執行輸出
運行它,無論是使用 SpEL在XML 還是注釋都顯示了同樣的結果:
package com.zaixian.core;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class App {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
Customer obj = (Customer) context.getBean("customerBean");
System.out.println(obj);
}
}
輸出結果
Customer [item=Item [name=itemA, qty=10], itemName=itemA]
