控制反转(IOC)、依赖注入(DI)之通过set方法注入

直接上例子


public interface Instrument {
    public void play();
}

一个乐器类,实现了乐器接口,

public class Saxophone implements Instrument {
    public Saxophone() {}

    @Override
    public void play() {
        System.out.println("TOOT TOOT TOOT");
    }
}

然后是一个乐器集合类

public class Instrumentalist {
    public Instrumentalist() {}

    public Instrumentalist(String song, String instrument) {
    }

    public void perform() throws PerformanceException {
        System.out.println("Playing " + song + " : ");
        instrument.play();
    }

    private String song;
    public void setSong(String song) {
        this.song = song;
    }

    private Instrument instrument;
    public void setInstrument(Instrument instrument) {
        this.instrument = instrument;
    }

}

一个set方法,设置的是String字符串,在perform中输出。一个是对象,在perform中调用他的弹奏乐器方法,也是输出。


最后还是看看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="saxophone" class="com.example.homework.set.Saxophone"/>


    <bean id="kenny" class="com.example.homework.set.Instrumentalist">
        <property name="song" value="Jingle Bells"/>
        <property name="instrument" ref="saxophone"/>
    </bean>
</beans>
这里使用的是property,而不是一开始的constructor方法了。如果是通过传构造函数的方法,那将是<constructor-arg index="0" value="15"/>
        <constructor-arg index="1" ref="poem"/>这样的形式。


最后在main中测试

public class SpringIdolKennyMain {
    public static void main(String[] args) {
        ApplicationContext ctx = new ClassPathXmlApplicationContext(
                "com/example/homework/set/spring-instrumentalist.xml"
        );
        Instrumentalist instrument = (Instrumentalist) ctx.getBean("kenny");
        System.out.println();

        instrument.perform();
    }
}

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值