两个接口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.
本文通过一个具体的示例展示了如何使用Spring框架进行依赖注入。示例中定义了Person和Axe两个接口,以及它们的实现类Chinese和StoneAxe。通过配置文件ApplicationContext.xml将StoneAxe实例注入到Chinese类中,并在TestSpringDemo类中调用useAxe方法展示StoneAxe的行为。
1844

被折叠的 条评论
为什么被折叠?



