spring 之集合装配

    当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型




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值