Spring-IoC-DI-基于xml的依赖注入-使用set方法进行注入(案例十二:在集合里面设置对象类型)

案例十二:在集合里面设置对象类型

(1)创建对象

public class Student {
    private String sname;
    private List<String> list;
    private List<Course> courseList;

    public void setSname(String sname) {
        this.sname = sname;
    }

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

    public void setCourseList(List<Course> courseList) {
        this.courseList = courseList;
    }

    public void show()
    {
        System.out.println(sname);
        System.out.println(list);
        System.out.println(courseList);
    }
}
 
public class Course {
    private String cname;
    public void setCname(String cname) {
        this.cname = cname;
    }
    @Override
    public String toString() {
        return "Course{" +
                "cname='" + cname + '\'' +
                '}';
    }
}

(2)配置bean

<?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:util="http://www.springframework.org/schema/util"
       xmlns:p="http://www.springframework.org/schema/p"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
                           http://www.springframework.org/schema/beans/spring-beans.xsd
                           http://www.springframework.org/schema/util
                           http://www.springframework.org/schema/util/spring-util.xsd">

    <!--  抽取集合  -->
    <util:list id="couserlist">
        <value>Java程序设计</value>
        <value>移动应用开发</value>
        <value>数据库</value>
    </util:list>


    <bean id="student" class="com.orz.spring.collection.Student">
        <property name="sname" value="李华"></property>
        <!--  注入集合属性      -->
        <property name="list" ref="couserlist"></property>
        <!--    在集合里面设置对象类型    -->
        <property name="courseList">
            <list>
                <ref bean="course1"></ref>
                <ref bean="course2"></ref>
            </list>
        </property>
    </bean>
    <bean id="course1" class="com.orz.spring.collection.Course">
        <property name="cname" value="Mysql"></property>
    </bean>
    <bean id="course2" class="com.orz.spring.collection.Course">
        <property name="cname" value="SQL"></property>
    </bean>

</beans>

(3)测试

package com.orz.spring.collection;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * @author orz
 * @create 2020-08-14 22:40
 */
public class Test2 {
    @Test
    public void test1()
    {
        ApplicationContext context=new ClassPathXmlApplicationContext("bean10.xml");
        Student student = context.getBean("student", Student.class);
        student.show();

    }
}

(4)结果

李华
[Java程序设计, 移动应用开发, 数据库]
[Course{cname='Mysql'}, Course{cname='SQL'}]

 

posted @ 2020-08-14 22:44  orz江小鱼  阅读(175)  评论(0编辑  收藏  举报