控制反转(IOC)、依赖注入(DI)之使用List、Properties注入集合

public class OneManBandList implements Performer{
    public OneManBandList() {}

    @Override
    public void perform() throws PerformanceException {
        for (Instrument instrument : instruments) {
            instrument.play();
        }
    }

    private Collection instruments;

    public void setInstruments(Collection instruments) {
        this.instruments = instruments;
    }
}

这一次xml中是这样配置的

xml version="1.0" encoding="UTF-8"?>
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">

    id="cymbal" class="com.example.homework.list.Cymbal"/>
    id="saxophone" class="com.example.homework.set.Saxophone"/>

    id="hank" class="com.example.homework.list.OneManBandList">
        name="instruments">
            
                bean="cymbal"/>
                bean="cymbal"/>
                bean="saxophone"/>
            
        
    


最后讲一下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中

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">

    id="hank" class="com.example.homework.properties.OneManBandProperties">
        name="instruments">
            
                key="CYMBAL">C C C
                key="HARMONICA">C C C
            
        
    


所有demo及jar包地址 https://github.com/xubinhong/SpringIocDemo

你可能感兴趣的:(后台)