Spring框架中XML配置文件注入集合(数组、LIST、MAP、SET)属性

Spring框架中XML配置文件注入集合属性

前言

某些类的属性是可能是集合,包括:数组、LISTMAPSET等集合,在Spring中同样可以使用XML配置文件的方式对属性进行注入。

创建测试类与属性

package com.action.spring.collectiontype;

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

public class Stud {
    
    
	
	private String[] str;	
	private List<String> lists;	
	private Map<String, String> maps;
	private Set<String> sets;
	
	public void setStr(String[] str) {
    
    
		this.str = str;
	}
	public void setLists(List<String> lists) {
    
    
		this.lists = lists;
	}
	public void setMaps(Map<String, String> maps) {
    
    
		this.maps = maps;
	}
	public void setSets(Set<String> sets) {
    
    
		this.sets = sets;
	}
	
	public void collectiontest() {
    
    
		
		System.out.println(Arrays.toString(str));
		System.out.println(lists);
		System.out.println(maps);
		System.out.println(sets);
		
	}

}

同样的,XML配置文件的属性注入方式都是依赖set方法,给每个属性配置set方法。

配置XML配置文件

<!-- 集合属性注入 -->
<bean id="stud" class="com.action.spring.collectiontype.Stud">
    <property name="str">
        <array>
            <value>办公室</value>
            <value>图书馆</value>
        </array>
    </property>
    <property name="lists">
        <list>
            <value>list1</value>
            <value>list2</value>
        </list>
    </property>
    <property name="maps">
        <map>
            <entry key="信息部" value="4楼"></entry>
            <entry key="人资部" value="7楼"></entry>
        </map>
    </property>
    <property name="sets">
        <set>
            <value>sets1</value>
            <value>sets2</value>
        </set>
    </property>
</bean>

编写方式基本相同,但需要对MAP类型的集合做出强调的是,在<map>子标签中,使用的是<entry>标签,其他的都是使用value标签。

建立调用类

使用另一个类对测试类进行调用,查看测试结果。

public class testSpring5 {
    
    
	
	@Test
	public void testAdd() throws Exception {
    
    
		
		ApplicationContext context =
				new FileSystemXmlApplicationContext("src/config/bean1.xml");
		
		Stud stud = context.getBean("stud", Stud.class);
		stud.collectiontest();

	}

}

调用结果

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/jerrygaoling/article/details/108715720