Spring EL支持三元運算符,執行“if then else”條件檢查。 例如,
condition ? true : false
Spring EL以注解形式
Spring EL三元運算符可使用@Value注解。在這個例子中,如果“itemBean.qtyOnHand”小於100,則設置“customerBean.warning”為true,否則將其設置為false。
package com.zaixian.core;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component("customerBean")
public class Customer {
@Value("#{itemBean.qtyOnHand < 100 ? true : false}")
private boolean warning;
public boolean isWarning() {
return warning;
}
public void setWarning(boolean warning) {
this.warning = warning;
}
@Override
public String toString() {
return "Customer [warning=" + warning + "]";
}
}
package com.zaixian.core;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component("itemBean")
public class Item {
@Value("99")
private int qtyOnHand;
public int getQtyOnHand() {
return qtyOnHand;
}
public void setQtyOnHand(int qtyOnHand) {
this.qtyOnHand = qtyOnHand;
}
}
輸出
Customer [warning=true]
Spring EL以XML形式
請參閱在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="customerBean" class="com.zaixian.core.Customer">
<property name="warning"
value="#{itemBean.qtyOnHand < 100 ? true : false}" />
</bean>
<bean id="itemBean" class="com.zaixian.core.Item">
<property name="qtyOnHand" value="99" />
</bean>
</beans>
輸出結果
Customer [warning=true]
在XML中,需要小於運算符使用"<"替換“<”。
上一篇:
Spring EL運算符實例
下一篇:
Spring EL Lists,Maps實例
