Spring的集合注入(XML方式)
首先创建一个CollectionBean.java文件,里面分别创建Array数组和List、Set、Map集合
public class CollectionBean { private String[] arrs; private List<String> list; private Set<String> set; private Map<String,String> map; public void setArrs(String[] arrs) { this.arrs = arrs; } public void setList(List<String> list) { this.list = list; } public void setSet(Set<String> set) { this.set = set; } public void setMap(Map<String, String> map) { this.map = map; } @Override public String toString() { return "CollectionBean [arrs=" + Arrays.toString(arrs) + ", list=" + list + ", set=" + set + ", map=" + map + "]"; } }
然后创建applicationContext.xml文件,
<bean id="collectionBean" class="com.spring.demo5.CollectionBean"> <!-- 数组类型 --> <property name="arrs"> <list> <value>王东</value> <value>赵洪</value> <value>李冠希</value> </list> </property> <!-- 注入list集合 --> <property name="list"> <list> <value>李兵</value> <value>赵如何</value> <value>邓凤</value> </list> </property> <!-- 注入set集合 --> <property name="set"> <set> <value>aaa</value> <value>bbb</value> <value>ccc</value> </set> </property> <!-- 注入Map集合 --> <property name="map"> <map> <entry key="aaa" value="111"/> <entry key="bbb" value="222"/> <entry key="ccc" value="333"/> </map> </property> </bean>
最后用一个测试方式来进行测试
@Test public void demo1() { ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml"); CollectionBean collectionBean = (CollectionBean) applicationContext.getBean("collectionBean"); System.out.println(collectionBean); }