開発者ドキュメント

Spring EL三項演算子(if-then-else)の例

Spring ELは

3項演算子

をサポートし、条件付き検査を行う場合は ”

if then else

“を実行します。例えば、

condition ? true : false

AnnotationのSpring EL

package com.mkyong.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.mkyong.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ファイルの同等のバージョンを参照してください。

<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”&gt

;

<bean id="customerBean" class="com.mkyong.core.Customer">
    <property name="warning"
                      value="#{itemBean.qtyOnHand < 100 ? true : false}"/>
</bean>
<bean id="itemBean" class="com.mkyong.core.Item">
    <property name="qtyOnHand" value="99"/>
</bean>

</beans>

__出力__

Customer[warning=true]…​.

XMLでは、演算子「

<

」を「** 」で置き換える必要があります。

ソースコードをダウンロードする

ダウンロードする – リンク://wp-content/uploads/2011/06/Spring3-EL-Ternary-Operator-Example.zip[Spring3-EL-Ternary-Operator-Example.zip](6 KB)

モバイルバージョンを終了