Spring EL ternary operator (if-then-else) example

Spring EL supports ternary operator , perform “if then else” conditional checking. For example,

condition ? true : false

Spring EL in Annotation

Spring EL ternary operator with @Value annotation. In this example, if “itemBean.qtyOnHand” is less than 100, then set “customerBean.warning” to true, else set it to false.

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; 
    }
}

Output

Customer [warning=true]

Spring EL in XML
See equivalent version in bean definition XML file.

<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.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>

Output

Customer [warning=true]

In XML, you need to replace less than operator "<" with "<".

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,841评论 18 139
  • 菜说: 对于美食的追求是人们与生俱来的本能,我们也曾在粗糙的食物里迷失了味觉,而所幸,我们并未迷失了对美味本质的把...
    小菜不卖菜阅读 359评论 0 0
  • 我先定义两个模型,一个是问题,一个是选项,一个问题可以有多个选项。一对多的类型。 我们要查询某个问题下有哪些选项可...
    amyhy阅读 1,517评论 0 1
  • 366环球汇跨境商城:三级营销业务详解。 一、店铺分销 1、分销商用户层级 跨境商城分销,采取三级销售形式,用户可...
    366环球汇_砂砾阅读 270评论 0 0
  • 这是一条让人尴尬的回答,我爱过的人并没有爱过我,在我第一次表白的时候,他就拒绝我了。但还是有一些甜蜜瞬间的,至少对...
    艾冬天阅读 499评论 0 0