以上笔记来源:
尚硅谷Spring零基础入门到进阶,一套搞定spring6全套视频教程(源码级讲解)https://www.bilibili.com/video/BV1kR4y1b7Qc
目录
10 依赖注入之注入数组类型属性
10.1 创建Emp实体类,Dept实体类
10.2 创建bean-diarray配置文件
10.3 创建测试类
10 依赖注入之注入数组类型属性
10.1 创建Emp实体类,Dept实体类
并且在Emp类中添加了一个字符数组private String[] loves,设置了该数组的getter()和setter()方法,用于对象类型的注入,并且在work方法中添加了展示数组信息的方法
package com.atguigu.spring6.iocxml.ditest;import java.util.Arrays;//员工类
public class Emp {private Dept dept;private String ename;private Integer age;private String[] loves;public String[] getLoves() {return loves;}public void setLoves(String[] loves) {this.loves = loves;}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();System.out.println(Arrays.toString(loves));}
}
10.2 创建bean-diarray配置文件
在其中添加了property标签,array标签以及value标签
<?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="dept" class="com.atguigu.spring6.iocxml.ditest.Dept"><property name="dname" value="安保部"></property></bean><bean id="emp" class="com.atguigu.spring6.iocxml.ditest.Emp"><property name="ename" value="haozihua"></property><property name="age" value="30"></property><!--对象类型的属性--><property name="dept" ref="dept"></property><property name="loves"><array><value>吃饭</value><value>睡觉</value><value>敲代码</value></array></property></bean></beans>
10.3 创建测试类
package com.atguigu.spring6.iocxml.ditest;import org.junit.jupiter.api.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;public class TestEmpTest {//数组类型数据注入@Testpublic void testUser4() {ApplicationContext context = new ClassPathXmlApplicationContext("bean-diarray.xml");Emp emp = context.getBean("emp", Emp.class);System.out.println("3 根据ID和class获取bean" + emp);emp.work();}
}