两个接口Person 和 Axe
package wei.peng;
public interface Person {
public void useAxe();
}
package wei.peng;
public interface Axe {
public String chop();
}
两个实现类Chinese 和 StoneAxe
package wei.peng;
public class Chinese implements Person {
private Axe axe;
public void setAxe(Axe axe) {
this.axe = axe;
}
@Override
public void useAxe() {
// TODO Auto-generated method stub
System.out.println(axe.chop());
}
}
package wei.peng;
public class StoneAxe implements Axe {
@Override
public String chop() {
// TODO Auto-generated method stub
return "Stone axe is so slow.... I want a steel axe.";
}
}
ApplicationContext.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-2.5.xsd"> <bean name="chinese" class="wei.peng.Chinese"> <property name="axe"> <ref local="StoneAxe" /> </property> </bean> <bean id="StoneAxe" class="wei.peng.StoneAxe"></bean> </beans>
Test类
package wei.peng;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
public class TestSpringDemo {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
ApplicationContext ctx = new FileSystemXmlApplicationContext("/src/applicationContext.xml");
Person per = (Person)ctx.getBean("chinese");
per.useAxe();
}
}
Test Result
log4j:WARN No appenders could be found for logger (org.springframework.context.support.FileSystemXmlApplicationContext). log4j:WARN Please initialize the log4j system properly. Stone axe is so slow.... I want a steel axe.