Spring EL列表,地图示例

在本文中,我们向您展示如何使用Spring EL从MapList中获取价值。 实际上,SpEL与Map和List配合使用的方式与Java完全相同。 参见示例:

//get map whete key = 'MapA'
	@Value("#{testBean.map['MapA']}")
	private String mapA;

	//get first value from list, list is 0-based.
	@Value("#{testBean.list[0]}")
	private String list;

注释中的Spring EL

在这里,创建了一个HashMapArrayList ,其中包含一些用于测试的初始数据。

package com.mkyong.core;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component("customerBean")
public class Customer {

	@Value("#{testBean.map['MapA']}")
	private String mapA;

	@Value("#{testBean.list[0]}")
	private String list;

	public String getMapA() {
		return mapA;
	}

	public void setMapA(String mapA) {
		this.mapA = mapA;
	}

	public String getList() {
		return list;
	}

	public void setList(String list) {
		this.list = list;
	}

	@Override
	public String toString() {
		return "Customer [mapA=" + mapA + ", list=" + list + "]";
	}

}
package com.mkyong.core;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.stereotype.Component;

@Component("testBean")
public class Test {

	private Map<String, String> map;
	private List<String> list;

	public Test() {
		map = new HashMap<String, String>();
		map.put("MapA", "This is A");
		map.put("MapB", "This is B");
		map.put("MapC", "This is C");

		list = new ArrayList<String>();
		list.add("List0");
		list.add("List1");
		list.add("List2");

	}

	public Map<String, String> getMap() {
		return map;
	}

	public void setMap(Map<String, String> map) {
		this.map = map;
	}

	public List<String> getList() {
		return list;
	}

	public void setList(List<String> list) {
		this.list = list;
	}

}

运行

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

输出量

Customer [mapA=This is A, list=List0]

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

	<bean id="customerBean" class="com.mkyong.core.Customer">
		<property name="mapA" value="#{testBean.map['MapA']}" />
		<property name="list" value="#{testBean.list[0]}" />
	</bean>

	<bean id="testBean" class="com.mkyong.core.Test" />

</beans>

下载源代码

下载它– Spring3-EL-Map-List-Example.zip (6 KB)

翻译自: https://mkyong.com/spring3/spring-el-lists-maps-example/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值