当Bean的属性是简单的字面值或者是其他对象的引用,我们可以通过使用“value”和“ref”很方便的满足我们的需要。但是如果Bean的属性是集合呢,那么就需要spring的集合装配。
首先看下spring提供的可供选择的集合有哪些:
来看看如何上手使用:
DepartMent类如下:
public class Department {
public String[] strs = {};
public List<Employee> emps = new ArrayList<Employee>();
public Map<String,Employee> maps = new HashMap<String, Employee>();
public Set<Employee> sets = new HashSet<>();
public Properties props = new Properties();
// 省略get和set方法
}
配置文件如下:
<?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.csdn.spring.wiring.collection.Department">
<property name="strs">
<array>
<value>攻城狮</value>
<value>程序猿</value>
<value>测试狗</value>
<value>产品猪</value>
</array>
</property>
<property name="emps">
<list>
<ref bean="emp1"/>
<ref bean="emp2"/>
<ref bean="emp3"/>
</list>
</property>
<property name="maps">
<map>
<entry key="1001" value-ref="emp1" />
<entry key="1002" value-ref="emp2" />
<entry key="1003" value-ref="emp3" />
</map>
</property>
<property name="sets">
<set>
<ref bean="emp1" />
<ref bean="emp2" />
<ref bean="emp3" />
</set>
</property>
<property name="props">
<props>
<prop key="1001">Kobe</prop>
<prop key="1002">Crawford</prop>
<prop key="1003">McGrady</prop>
</props>
</property>
</bean>
<bean id="emp1" class="com.csdn.spring.wiring.collection.Employee" />
<bean id="emp2" class="com.csdn.spring.wiring.collection.Employee" />
<bean id="emp3" class="com.csdn.spring.wiring.collection.Employee" />
</beans>
- list:装配list类型的值,允许重复
- set:装配set类型的值,不允许重复
- map:装配map类型的值,名称和值可以为任意类型
- props:装配properties类型的值,名称和值必须是Strig型