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

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

    • 前言
    • 创建测试类与属性
    • 配置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>list1value>
            <value>list2value>
        list>
    property>
    <property name="maps">
        <map>
            <entry key="信息部" value="4楼">entry>
            <entry key="人资部" value="7楼">entry>
        map>
    property>
    <property name="sets">
        <set>
            <value>sets1value>
            <value>sets2value>
        set>
    property>
bean>

编写方式基本相同,但需要对MAP类型的集合做出强调的是,在子标签中,使用的是标签,其他的都是使用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();

	}

}

调用结果

Spring框架中XML配置文件注入集合(数组、LIST、MAP、SET)属性_第1张图片

你可能感兴趣的:(Spring学习,spring,java,xml,bean)