Spring-集合类型装配

来源:互联网 发布:外籍模特知乎 编辑:程序博客网 时间:2024/05/21 09:21

1、新建集合类

CollectionBean.java

/* *@Author swxctx *@time 2016年9月27日 */package com.sw.gather;import java.util.List;import java.util.Map;import java.util.Properties;import java.util.Set;public class CollectionBean {private List myList;private Set mySet;private Map myMap;private Properties myProperties;public List getMyList() {return myList;}public void setMyList(List myList) {System.out.println("List类型:"+myList.getClass().getName());this.myList = myList;}public Set getMySet() {return mySet;}public void setMySet(Set mySet) {System.out.println("Set类型:"+mySet.getClass().getName());this.mySet = mySet;}public Map getMyMap() {return myMap;}public void setMyMap(Map myMap) {System.out.println("Map类型:"+myMap.getClass().getName());this.myMap = myMap;}public Properties getMyProperties() {return myProperties;}public void setMyProperties(Properties myProperties) {System.out.println("Properties类型:"+myProperties.getClass().getName());this.myProperties = myProperties;}}
2、配置文件

beans.xml:

<?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-2.5.xsd"><bean id="collectionBean" class="com.sw.gather.CollectionBean"><property name="myList"><list><value>aa</value><value>bb</value></list></property><property name="mySet"><set><value>cc</value><value>dd</value></set></property><property name="myMap"><map><entry key="1" value="ee"></entry><entry key="2" value="ff"></entry></map></property><property name="myProperties"><props><prop key="3">gg</prop><prop key="4">hh</prop></props></property></bean></beans>
3、测试类

/* *@Author swxctx *@time 2016年9月27日 */package com.sw.Test;import static org.junit.Assert.*;import org.junit.BeforeClass;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;import com.sw.gather.CollectionBean;public class Test {@BeforeClasspublic static void setUpBeforeClass() throws Exception {}@org.junit.Testpublic void test() {ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");CollectionBean collectionBean = (CollectionBean)ctx.getBean("collectionBean");System.out.println("---List---");for(Object s:collectionBean.getMyList()){System.out.println(s);}System.out.println("---Set---");for(Object s:collectionBean.getMySet()){System.out.println(s);}System.out.println("---Map---");for(Object s:collectionBean.getMyMap().keySet()){System.out.println(s+"="+collectionBean.getMyMap().get(s));}System.out.println("---Properties---");for(Object s:collectionBean.getMyProperties().keySet()){System.out.println(s+"="+collectionBean.getMyProperties().get(s));}}}

执行结果如下:


0 0