IOC操作Bean管理(xml注入集合属性)
- 注入数组类型的属性
- 注入list集合类型属性
- 注入Map集合类型属性
1 创建类,定义数组、list、map、set类型属性,生成对应的set方法
package com.cy.collectiontype;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class Stu {
/*1 数组类型属性*/
private String[] courses;
/*2 list集合类型属性*/
private List<String> list;
/*3 map集合类型属性*/
private Map<String,String> map;
/*4 set集合类型属性*/
private Set<String> set;
public void setCourses(String[] courses) {
this.courses = courses;
}
public void setList(List<String> list) {
this.list = list;
}
public void setMap(Map<String, String> map) {
this.map = map;
}
public void setSet(Set<String> set) {
this.set = set;
}
}
2 在spring配置文件进行配置
<?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">
<!--1 集合类型属性注入-->
<bean id="stu" class="com.cy.collectiontype.Stu">
<!--数组类型属性注入-->
<property name="courses">
<array>
<value>Java课程</value>
<value>数据库课程</value>
</array>
</property>
<!--list集合类型属性注入-->
<property name="list">
<list>
<value>张三</value>
<value>小三</value>
</list>
</property>
<!--map属性注入-->
<property name="map">
<map>
<entry key="努力" value="经验"></entry>
<entry key="运气" value="成功"></entry>
</map>
</property>
<!--set属性注入-->
<property name="set">
<set>
<value>Java</value>
<value>C++</value>
<value>Java</value>
</set>
</property>
</bean>
</beans>
3 测试
package com.cy.collectiontype;
public void test(){
System.out.println(Arrays.toString(courses));
System.out.println(list);
System.out.println(map);
System.out.println(set);
}
package test;
import com.cy.collectiontype.Stu;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestCollection {
@Test
public void testCollection(){
ApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml");
Stu stu = context.getBean(Stu.class);
stu.test();
}
}
4 优化
在集合里面设置对象类型的值
xml配置
<!--注入list集合类型-->
<property name="courseList">
<list>
<ref bean="course1"></ref>
<ref bean="course2"></ref>
</list>
</property>
</bean>
<bean id="course1" class="com.cy.collectiontype.Course">
<property name="cname" value="Spring"></property>
</bean>
<bean id="course2" class="com.cy.collectiontype.Course">
<property name="cname" value="Mybatis"></property>
</bean>
提取集合中公共部分
1 在spring配置文件中引入名称空间util
2 使用util标签完成list集合注入
https://www.bilibili.com/video/BV1Vf4y127N5?p=14&spm_id_from=pageDriver