工程结构:
Stu学生类:
/**
* @Author Dali
* @Date 2021/5/4 13:19
* @Version 1.0
* @Description
*/
public class Stu {
//学生所学的多们课程
private List<Course> coursesList; //TODO 在集合里面设置对象类型值
public void setCoursesList(List<Course> coursesList) {
this.coursesList = coursesList;
}
public void test() {
System.out.println(coursesList);
}
}
package com.youliao.spring5.collertiontype;
/**
* @Author Dali
* @Date 2021/5/4 14:38
* @Version 1.0
* @Description
*/
public class Course {
private String cname; //课程名称
public void setCname(String cname) {
this.cname = cname;
}
@Override
public String toString() {
return "Course{" +
"cname='" + cname + '\'' +
'}';
}
}
集合里面设置对象类型值,通过bean1.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" xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/util https://www.springframework.org/schema/util/spring-util.xsd">
<!--1、集合类型的属性注入-->
<bean id="stu" class="com.youliao.spring5.collertiontype.Stu">
<!--注入List集合类型。值是对象-->
<property name="coursesList">
<list>
<ref bean="course1"></ref>
<ref bean="course2"></ref>
</list>
</property>
</bean>
<!--创建多个course对象-->
<bean id="course1" class="com.youliao.spring5.collertiontype.Course">
<property name="cname" value="Spring5框架"></property>
</bean>
<bean id="course2" class="com.youliao.spring5.collertiontype.Course">
<property name="cname" value="VUE框架"></property>
</bean>
</beans>
TestSpring5Demo1测试类:
public class TestSpring5Demo1 {
@Test
public void testCollection() {
//1 加载 spring 配置文件
ApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml");
//2 获取配置创建的对象
Stu stu = context.getBean("stu", Stu.class);
stu.test();
}
}
输出结果:
版权声明:本文为qq_36833593原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。