在实际的开发中,有的bean中会有集合属性,如下:
package com.sevenhu.domain; import java.util.List; /** * Created by hu on 2016/3/31. */ public class RichMen { private List<Car> cars; public void setCars(List<Car> cars) { this.cars = cars; } }
那么集合属性的配置如下:
<bean id="richMan1" class="com.sevenhu.domain.RichMen"> <property name="cars"> <!--使用list集合来装配集合属性--> <list> <ref bean="car1"/> <ref bean="car2"/> </list> </property> </bean>
或还可以如下配置,将集合属性在外部配置,可以实现共享,如下:
<!--声明集合类型的bean--> <util:list id="cars"> <ref bean="car1"/> <ref bean="car2"/> </util:list> <bean id="richMan2" class="com.sevenhu.domain.RichMen"> <property name="cars" ref="cars"></property> </bean>
那么Map类型的集合属性的配置过程如下,首先,建立一个含有Map类型集合属性的bean类:
package com.sevenhu.domain; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import java.util.Iterator; import java.util.Map; import java.util.Set; /** * Created by hu on 2016/3/31. */ public class MapPropertyTest { private Map nameAndAge; public void setNameAndAge(Map nameAndAge) { this.nameAndAge = nameAndAge; } @Override public String toString(){ String str=""; String tempStr=""; Set<Map.Entry> entrySet=nameAndAge.entrySet(); Iterator<Map.Entry> iterator=entrySet.iterator(); while (iterator.hasNext()){ Map.Entry entry=iterator.next(); tempStr= entry.getKey()+":"+entry.getValue(); str=str+tempStr+" "; } return str; } public static void main(String[] args){ ApplicationContext applicationContext=new ClassPathXmlApplicationContext("beans.xml"); MapPropertyTest mapPropertyTest= (MapPropertyTest) applicationContext.getBean("mapPropertyTest"); System.out.println(mapPropertyTest); } }
然后配置代码如下:
<!--Map类型的集合属性--> <bean id="mapPropertyTest" class="com.sevenhu.domain.MapPropertyTest"> <property name="nameAndAge"> <map> <entry> <key> <value>hujingwei</value> </key> <value>23</value> </entry> </map> </property> </bean>