美文网首页JAVA后台开发_从入门到精通
19 Spring EL三元运算(if-then-else)实

19 Spring EL三元运算(if-then-else)实

作者: 笑Skr人啊 | 来源:发表于2017-08-21 16:57 被阅读42次

Spring EL支持三元运算符,执行“if then else”条件检查。 例如,

condition ? true : false

Spring EL以注解形式

Spring EL三元运算符可使用@Value注解。在这个例子中,如果“itemBean.qtyOnHand”小于100,则设置“customerBean.warning”为true,否则将其设置为false

package com.gp6.el.ternary;

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.gp6.el.ternary;

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

}
package com.gp6.el.ternary;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Test {

     public static void main( String[] args ) {
            
         ApplicationContext context = new ClassPathXmlApplicationContext(
                    "com/gp6/el/ternary/el_ternary.xml");

         Customer customer = (Customer) context.getBean("customerBean");
         System.out.println(customer);
    }
    
}



输出

Customer [warning=true]

Spring EL以XML形式

<!-- 以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">
 
    <bean id="customerBean" class="com.gp6.el.ternary.Customer">
        <property name="warning" 
                          value="#{itemBean.qtyOnHand < 100 ? true : false}" />
    </bean>
 
    <bean id="itemBean" class="com.gp6.el.ternary.Item">
        <property name="qtyOnHand" value="99" />
    </bean>
</beans> 

  • 在XML中,需要小于运算符使用& lt;替换“<”。

相关文章

网友评论

    本文标题:19 Spring EL三元运算(if-then-else)实

    本文链接:https://www.haomeiwen.com/subject/vuchdxtx.html