以前講解了Spring的基本類型和bean引用的注入,接下來學習一下複雜集合類型的注入,例如:List、Set、Map等。java
對於程序員來講,掌握多種語言是基本的技能。程序員
咱們這裏作了一個小例子,程序員們是一個Bean實例,而掌握的編程語言則是放入一個集合類型中進行注入。spring
簡單的來講:編程
List是一種按照序號標識的集合,編程語言
Set與List類似可是元素不容許重複,ide
Map則是一種自定的鍵值對,鍵值均可以是任意的類型。學習
public class Programmer { public Programmer(){} //List 與 Set的注入 private Collection<Language> language; public void setLanguage(Collection<Language> language){ this.language = language; } public void working(){ for(Language lang : language){ System.out.println("working on "+lang.using()); } } //Map的注入 private Map<String,Language> lang; public void setLang(Map<String,Language> lang){ this.lang = lang; } public void studying(){ for(String key : lang.keySet()){ System.out.print(key+" : "); Language language = lang.get(key); System.out.println("studying on "+language.using()); } } }
其餘須要的一些接口和實現類this
public interface Language { public String using(); }
public class Java implements Language{ public String using() { return "Java"; } }
public class Cpp implements Language{ public String using() { return "C++"; } }
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> <bean id="java" class="com.spring.test.collector.Java"/> <bean id="cpp" class="com.spring.test.collector.Cpp"/> <bean id="xingoo" class="com.spring.test.collector.Programmer"> <property name="language"> <list> <ref bean="java"/> <ref bean="cpp"/> </list> </property> </bean> <bean id="halo" class="com.spring.test.collector.Programmer"> <property name="language"> <set> <ref bean="java"/> </set> </property> </bean> <bean id="zhang3" class="com.spring.test.collector.Programmer"> <property name="lang"> <map> <!-- key鍵爲String key-ref鍵爲其餘bean的引用 --> <!-- value值爲String value-ref值爲其餘bean的引用 --> <entry key="java" value-ref="java"/> <entry key="cpp" value-ref="cpp"/> </map> </property> </bean> </beans>
public class test { public static void main(String[] args) { ApplicationContext ctx = new ClassPathXmlApplicationContext("bean.xml"); System.out.println("[xingoo]"); Programmer programmer = (Programmer)ctx.getBean("xingoo"); programmer.working(); System.out.println("[halo]"); Programmer programmer1 = (Programmer)ctx.getBean("halo"); programmer1.working(); System.out.println("[zhang3]"); Programmer programmer2 = (Programmer)ctx.getBean("zhang3"); programmer2.studying(); } }
[xingoo] working on Java working on C++ [halo] working on Java [zhang3] java : studying on Java cpp : studying on C++