public class OneManBandList implements Performer{ public OneManBandList() {} @Override public void perform() throws PerformanceException { for (Instrument instrument : instruments) { instrument.play(); } } private Collection<Instrument> instruments; public void setInstruments(Collection<Instrument> instruments) { this.instruments = instruments; } }
这一次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.xsd"> <bean id="cymbal" class="com.example.homework.list.Cymbal"/> <bean id="saxophone" class="com.example.homework.set.Saxophone"/> <bean id="hank" class="com.example.homework.list.OneManBandList"> <property name="instruments"> <list> <ref bean="cymbal"/> <ref bean="cymbal"/> <ref bean="saxophone"/> </list> </property> </bean> </beans>
最后讲一下Properties的方法
public class OneManBandProperties implements Performer{ @Override public void perform() throws PerformanceException { for (Iterator iter = instruments.keySet().iterator();iter.hasNext();) { String key = (String) iter.next(); System.out.println(key + " : " + instruments.getProperty(key)); } } private Properties instruments; public void setInstruments(Properties instruments) { this.instruments = instruments; } }乐器集合代码instruments.getProperty(key)就是类似与map一样取。
xml中
<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="hank" class="com.example.homework.properties.OneManBandProperties"> <property name="instruments"> <props> <prop key="CYMBAL">C C C</prop> <prop key="HARMONICA">C C C</prop> </props> </property> </bean> </beans>
所有demo及jar包地址 https://github.com/xubinhong/SpringIocDemo