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