1.在spring中为集合属性进行属性注入
1.1集合属性类
//数组属性
private String[] arr;
//list属性
private List list;
//Map属性
private Map<Integer,String> map;
//set属性
private Set set;
//类做元素的list属性
private List courseList;
1.2xml配置文档的配置
1.2.1对数组的属性注入
< property name="arr">
< array>
< value>10086< /value>
< value>1008611< /value>
< value>254120< /value>
< /array>
< /property>
1.2.2对list的属性注入
< property name="list">
< list>
< value>123< /value>
< value>456< /value>
< value>789< /value>
< /list>
< /property>
1.2.3对set的属性注入
< property name="set">
< set>
< value>张三< /value>
< value>李四< /value>
< value>梨花< /value>
< /set>
< /property>
1.2.4对map的属性注入
< property name="map">
< map>
< entry key="12" value="java">< /entry>
< entry key="13" value="mysql">< /entry>
< /map>
< /property>
1.2.5对元素为类的list的属性注入
先创建对象,注入相应的属性
< bean id=“course1” class=“ams.course”>
< property name=“name” value=“java程序设计”>< /property>
< /bean>
< bean id=“course2” class=“ams.course”>
< property name=“name” value=“Spring学习视频”>< /property>
< /bean>
在将这些对象注入到list中
< property name=“courseList”>
< list>
< ref bean=“course1”>
< ref bean=“course2”>
< /list>
< /property>
2.小结
数组,list,set都是通过< value>标签完成对属性的注入的,将需要注入的属性写到value标签中就可以。map的属性注入,需要用到entry标签,标签中有key和value两个属性。而用类做元素的list,map登集合类型,类属性的注入,都是通过先用bean标签实例化完成对象,在使用ref标间进行注入。
3.将list等集合属性的注入公有化
对于一个list属性需要进行多次的属性注入这种情况,为了减少代码重复,可以将这部分集合属性设置成一个公共的属性,然后其他的类需要使用的时候可以直接用。
/*
这种方式,需要使用到前面的p命名空间,先声明一个p命名空间和一个util空间,然
后再将最后一行的xsi中的代码复制,将bean改成util
*/
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:util="http://www.springframework.org/schema/util"
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
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">
<util:list id="list">
<value>张三</value>
<value>李四</value>
<value>王二</value>
</util:list>
<bean id="courseList" class="ams.courseList">
<property name="stu" ref="list"></property>
</bean>
</beans>