Spring6梳理11——依赖注入之注入List集合类型属性

发布于:2024-10-12 ⋅ 阅读:(7) ⋅ 点赞:(0)

以上笔记来源:
尚硅谷Spring零基础入门到进阶,一套搞定spring6全套视频教程(源码级讲解)https://www.bilibili.com/video/BV1kR4y1b7Qc

11  依赖注入之注入List集合类型属性

11.1  创建实体类Emp以及Dept

Dept类中添加了遍历Emplist的方法

package com.atguigu.spring6.iocxml.ditest;


//员工类
public class Emp {
    private Dept dept;
    private String ename;
    private Integer age;

    public Dept getDept() {
        return dept;
    }

    public void setDept(Dept dept) {
        this.dept = dept;
    }

    public String getEname() {
        return ename;
    }

    public void setEname(String ename) {
        this.ename = ename;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public void work() {
        System.out.println(ename + "工作到了" + age);
        dept.info();
    }
}
package com.atguigu.spring6.iocxml.ditest;


import java.util.List;

//部门类
public class Dept {
    private String dname;
    private List<Emp> empList;

    public List<Emp> getEmpList() {
        return empList;
    }

    public void setEmpList(List<Emp> empList) {
        this.empList = empList;
    }

    public String getDname() {
        return dname;
    }

    public void setDname(String dname) {
        this.dname = dname;
    }

    public void info() {
        System.out.println("部门名称是:"+dname);
        for (Emp emp : empList) {
            System.out.println(emp.getEname());
        }
    }

}

11.2  创建配置文件bean-dilist.xml

在引入list属性类型时,<property>标签的name属性为实体类变量的名称,在list标签中添加<value></value>或者<ref></ref>

<?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="empone" class="com.atguigu.spring6.iocxml.ditest.Emp">
        <property name="ename" value="haozihua"></property>
        <property name="age" value="28"></property>
    </bean>
    <bean id="emptwo" class="com.atguigu.spring6.iocxml.ditest.Emp">
        <property name="ename" value="lucy"></property>
        <property name="age" value="32"></property>
    </bean>
    <bean id="dept" class="com.atguigu.spring6.iocxml.ditest.Dept">
        <property name="dname" value="技术部"></property>
        <property name="empList">
        <list>
            <ref bean="empone"></ref>
            <ref bean="emptwo"></ref>
        </list>
        </property>
    </bean>
</beans>

11.3  创建测试类方法

在引入list属性类型时,<property>标签的name属性为实体类变量的名称,在list标签中添加<value></value>或者<ref></ref>

    @Test
    public void testUser5() {
        ApplicationContext context = new ClassPathXmlApplicationContext("bean-dilist.xml");
        Dept dept = context.getBean("dept", Dept.class);
        System.out.println("3 根据ID和class获取bean" + dept);
//        emp.work();
        dept.info();
    }

11.4  运行结果