直接上例子
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