SpringEL-操作List、Map

这个例子演示SpEL表达式怎样从List、Map集合中取值,示例如下:

一、编写Bean类

TestCollection类,用于创建Map和List对象

package com.yiidian.collection;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
 * 
 * @author http://www.yiidian.com
 *
 */
public class TestCollection {
	private Map<String, String> nameMap;
	private List<String> teleList;

	public TestCollection() {
		nameMap = new HashMap<String, String>();
		nameMap.put("001", "张三");
		nameMap.put("002", "李四");
		nameMap.put("003", "王五");

		teleList = new ArrayList<String>();
		teleList.add("13422223333");
		teleList.add("13544446666");
		teleList.add("13788889999");

	}

	public Map<String, String> getNameMap() {
		return nameMap;
	}

	public void setNameMap(Map<String, String> nameMap) {
		this.nameMap = nameMap;
	}

	public List<String> getTeleList() {
		return teleList;
	}

	public void setTeleList(List<String> teleList) {
		this.teleList = teleList;
	}
	
}

Customer类:

package com.yiidian.domain;

import java.io.Serializable;
/**
 * 
 * @author http://www.yiidian.com
 *
 */
public class Customer implements Serializable{
	private String name;
	private String telephone;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getTelephone() {
		return telephone;
	}
	public void setTelephone(String telephone) {
		this.telephone = telephone;
	}
	@Override
	public String toString() {
		return "Customer [name=" + name + ", telephone=" + telephone + "]";
	}
	
}

二、配置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="testCollection" class="com.yiidian.collection.TestCollection"></bean>

	<bean id="customer" class="com.yiidian.domain.Customer">
		<property name="name" value="#{testCollection.nameMap['001']}"/>
		<property name="telephone" value="#{testCollection.teleList[0]}"/>
	</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);
	}

}

四、运行结果

 

源码下载:http://pan.baidu.com/s/1hsCK0S0

热门文章

优秀文章