Spring在整合其餘框架時在配置文件中可能會涉及到複雜類型屬性的注入,如下舉例說明:java
1.數組類型spring
2.List集合類型數組
3.Set集合類型app
4.Map集合類型框架
5.Properties屬性類型ide
直接上代碼:測試
實體類:CollectionBean.javathis
package com.imooc.ioc.demo5; import java.util.*; /** * Spring複雜類型的集合注入 */ public class CollectionBean { private String[] arrs; //數組類型 private List<String> list; //list類型 private Set<String> set; //set類型 private Map<String , Integer> map; //map類型 private Properties properties; //屬性類型 public String[] getArrs() { return arrs; } public void setArrs(String[] arrs) { this.arrs = arrs; } public List<String> getList() { return list; } public void setList(List<String> list) { this.list = list; } public Set<String> getSet() { return set; } public void setSet(Set<String> set) { this.set = set; } public Map<String, Integer> getMap() { return map; } public void setMap(Map<String, Integer> map) { this.map = map; } public Properties getProperties() { return properties; } public void setProperties(Properties properties) { this.properties = properties; } @Override public String toString() { return "CollectionBean{" + "arrs=" + Arrays.toString(arrs) + ", list=" + list + ", set=" + set + ", map=" + map + ", properties=" + properties + '}'; } }
配置文件:applicationContext.xmlspa
<?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="collectionBean" class="com.imooc.ioc.demo5.CollectionBean"> <!--數組類型注入--> <property name="arrs"> <list> <value>111</value> <value>222</value> <value>333</value> </list> </property> <!--list類型注入--> <property name="list"> <list> <value>aaa</value> <value>bbb</value> <value>ccc</value> </list> </property> <!--set類型注入--> <property name="set"> <set> <value>ddd</value> <value>eee</value> <value>fff</value> </set> </property> <!--map類型注入--> <property name="map"> <map> <entry key="aaa" value="111"></entry> <entry key="bbb" value="222"></entry> <entry key="ccc" value="333"></entry> </map> </property> <!--properties類型注入--> <property name="properties"> <props> <prop key="aaa">555</prop> <prop key="bbb">666</prop> <prop key="ccc">777</prop> </props> </property> </bean> </beans>
測試類:SpringDemo5.javacode
package com.imooc.ioc.demo5; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class SpringDemo5 { @Test public void demo1(){ ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml"); CollectionBean collectionContext = (CollectionBean)applicationContext.getBean("collectionBean"); System.out.println(collectionContext); } }
測試類輸出結果: