控制反转(IOC)、依赖注入(DI)之通过构造函数注入对象

上文的例子中仅仅接受简单的构造函数,这里我们对上文的例子进行扩展(继承),使得他可以接受对象的构造函数,并且我们在xml中也增加对应属性。


这是他的新技能

public class Poem {
    String poem ="苍茫的天涯是我的爱,连绵的青山脚下花正开";

    public void recite() {
        System.out.println(poem);
    }
}

我们继承刚刚那个对象

public class PoeticJuggler extends Juggler {
    private Poem poem;

    public PoeticJuggler(int beanBags, Poem poem) {
        super(beanBags);
        this.poem = poem;
    }

    public void perform() throws PerformanceException {
        super.perform();
        System.out.println("WHILE RECITING...");
        poem.recite();
    }
}
这个新的子类就是现在学会了诗歌的他,接受两个参数,其中一个是诗歌类。并且继承了他的表演方法,调用了父类的表演方法(即把玩球),给他扩充了新的方法,朗诵诗歌。


前面的东西我们都知道,现在看看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="poem" class="com.example.homework.constructor_object.Poem"/>
    <bean id="poeticJuggler" class="com.example.homework.constructor_object.PoeticJuggler">
        <constructor-arg index="0" value="15"/>
        <constructor-arg index="1" ref="poem"/>
    </bean>

</beans>
先声明下poom类,再ref引用这个pome即可。


main函数中跑一下

public class JugglerExtendsMain {
    public static void main(String[] args) {
        ApplicationContext ctx = new ClassPathXmlApplicationContext(
                "com/example/homework/constructor_object/spring-juggler-extends.xml"
        );
        Performer performer = (Performer) ctx.getBean("poeticJuggler");
        System.out.println();
        System.out.println();

        performer.perform();
    }
}

输出

Playing 15 in his hand
WHILE RECITING...
苍茫的天涯是我的爱,连绵的青山脚下花正开


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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值