使用SpringEL表達式進行三目運算


原文鏈接:http://www.yiidian.com/spring/spring-el-three-mesh-operator.html

SpEL支持三目運算符,以此來實現條件語句。

一、編寫Bean類

Item類:

package com.yiidian.domain;
/**
 * 
 * @author http://www.yiidian.com
 *
 */
public class Item {
	
	private int qtyOnHand;
    public int getQtyOnHand() {
        return qtyOnHand;
    }
 
    public void setQtyOnHand(int qtyOnHand) {
        this.qtyOnHand = qtyOnHand;
    }
}

Customer類:

package com.yiidian.domain;

import java.io.Serializable;
/**
 * 
 * @author http://www.yiidian.com
 *
 */
public class Customer implements Serializable{
    private boolean warning;
    public boolean isWarning() {
        return warning;
    }
    public void setWarning(boolean warning) {
        this.warning = warning;
    }
 
    @Override
    public String toString() {
        return "Customer [warning=" + warning + "]";
    }
}

二、配置applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:p="http://www.springframework.org/schema/p" 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.xsd">
	
	<bean id="customer" class="com.yiidian.domain.Customer">
        <property name="warning" value="#{itemBean.qtyOnHand &lt; 100 ? true : false}" />
    </bean>
 
    <bean id="itemBean" class="com.yiidian.domain.Item">
        <property name="qtyOnHand" value="99" />
    </bean>


</beans>

三、編寫測試類

package com.yiidian.test;

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

import com.yiidian.domain.Customer;

/**
 * @author http://www.yiidian.com
 * 
 */
public class Demo1 {

	@Test
	public void test1() {
		ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
		Customer customer = (Customer)context.getBean("customer");
		System.out.println(customer);
	}

}

四、運行結果

file

源碼下載:http://pan.baidu.com/s/1qYmLKfE
file

歡迎關注我的公眾號::一點教程。獲得獨家整理的學習資源和日常干貨推送。
如果您對我的系列教程感興趣,也可以關注我的網站:yiidian.com


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM