Spring EL三項演算子(if-then-else)の例
Spring ELはternary operatorをサポートし、「if then else」条件付きチェックを実行します。 例えば、
condition ? true : false
注釈のSpring EL
@Valueアノテーション付きのSpringEL三項演算子。 この例では、「itemBean.qtyOnHand」が100未満の場合は、「customerBean.warning」をtrueに設定し、そうでない場合はfalseに設定します。
package com.example.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.example.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]
XMLのSpring EL
Bean定義XMLファイルで同等のバージョンを参照してください。
出力
Customer [warning=true]
XMLでは、未満の演算子「<」を「<」に置き換える必要があります。
ソースコードをダウンロード
ダウンロード-Spring3-EL-Ternary-Operator-Example.zip(6 KB)