Spring IOC List Set Map 注入

1.项目创建

https://blog.csdn.net/zhaolinxuan1/article/details/84897949

https://blog.csdn.net/zhaolinxuan1/article/details/84932897

2.User类

package com;

import java.util.List;
import java.util.Map;
import java.util.Set;

public class User {
	private Set<String> sets;
	
	private List<String> list;
	
	private Map<String ,String> map;
	
	public Set<String> getSets() {
		return sets;
	}
	public void setSets(Set<String> sets) {
		this.sets = sets;
	}
	public List<String> getList() {
		return list;
	}
	public void setList(List<String> list) {
		this.list = list;
	}
	public Map<String, String> getMap() {
		return map;
	}
	public void setMap(Map<String, String> map) {
		this.map = map;
	}

}

3.beans.xml

注:<property name="">需要和User中的属性对应

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd">
	<bean id="user" class="com.User">
		<!-- set -->
		<property name="sets">
			<set>
			<value>set1</value>
			<value>set2</value>
			<value>set3</value>
			</set>
		</property>
		<!-- list -->
		<property name="list">
			<list>
			<value>list1</value>
			<value>list2</value>
			<value>list3</value>
			</list>
		</property>
		<!-- map -->
		<property name="map">
			<map>
			<entry key="1">
			<value>map1</value>
			</entry>
			<entry key="2">
			<value>map2</value>
			</entry>
			</map>
		</property>
	</bean>
</beans>

4.测试

public class Test {
	public static void main(String[] args) {
		BeanFactory bfUser=new ClassPathXmlApplicationContext("beans.xml");
		User user=(User) bfUser.getBean("user");
		System.out.println(user);
		/*****************  list  *******************/
		System.out.println(user.getList());
		List<String> list=user.getList();
		Iterator<String> iterator= list.iterator();
		while(iterator.hasNext()) {
			System.out.println(iterator.next());
		}
		System.out.println("**************************");
		/*****************  map  *******************/
		System.out.println(user.getMap());
		Map<String,String> map=user.getMap();
		Iterator<Map.Entry<String, String>> iteratorMap=map.entrySet().iterator();
		while(iteratorMap.hasNext()) {
			Map.Entry<String, String> entry=iteratorMap.next();
			System.out.println("key:"+entry.getKey()+";value:"+entry.getValue());
		}
		System.out.println("**************************");
		/*****************  set  *******************/
		System.out.println(user.getSets());
		Set<String> sets=user.getSets();
		Iterator iteratorSet=sets.iterator();
		while(iteratorSet.hasNext()) {
			System.out.println(iteratorSet.next());
		}
				
	}
}

5.测试结果

©️2020 CSDN 皮肤主题: 创作都市 设计师:CSDN官方博客 返回首页