控制反转(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<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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值