6.Bean管理-注入集合属性.md

zhanglei 2022年05月30日 318次浏览

6.Bean管理-注入集合属性

Collection类

package Spring5.Collection;

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

public class Collection {
    private String[] course;

    private List<String> list;

    private Map<String,String>map;

    private Set set;

    public void setCourse(String[] course) {
        this.course = course;
    }

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

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

    public void setSet(Set set) {
        this.set = set;
    }
    public void show(){
        System.out.println(Arrays.toString(course));
        System.out.println(list);
        System.out.println(map);
        System.out.println(set);
    }
}

bean5.xml

<?xml version="1.0" encoding="UTF-8"?>
<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.xsd">
    <bean id="Collection" class="Spring5.Collection.Collection">
       <!--数组类型属性注入-->
        <property name="course">
            <array>
                <value>数据结构与算法</value>
                <value>mysql</value>
            </array>
        </property>

        <!--List类型属性注入-->
        <property name="list">
            <list>
                <value>张三</value>
                <value>李四</value>
            </list>
        </property>

        <!--Map类型 属性注入-->
        <property name="map">
            <map>
                <entry key="00" value="11"></entry>
                <entry key="zl" value="ltt"></entry>
            </map>
        </property>

        <!--Set类型属性注入-->
        <property name="set">
            <set>
                <value>数学</value>
                <value>英语</value>
                <value>英语</value>
            </set>
        </property>
    </bean>
</beans>

Test类

public class TEST {
  
    //bean管理:注入集合属性
    @Test
    public void testBean5() {
        ApplicationContext context = new ClassPathXmlApplicationContext("bean5.xml");
        Collection c = context.getBean("Collection", Collection.class);
        c.show();
    }
}

测试结果

[数据结构与算法, mysql]
[张三, 李四]
{00=11, zl=ltt}
[数学, 英语]