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

来源:互联网 发布:linux 文件共享服务器 编辑:程序博客网 时间:2024/05/17 23:46

上文的例子中仅仅接受简单的构造函数,这里我们对上文的例子进行扩展(继承),使得他可以接受对象的构造函数,并且我们在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 0
原创粉丝点击