1. 首先新建2个接口,Person(人),Axe(斧头)接口。
Person接口:
package springtest;
//定义Person接口
public interface Person {
//Person接口里定义一个使用斧头的方法
public void useAxe();
}
Axe接口:
package springtest;
//定义Axe接口
public interface Axe {
//Axe接口有个砍柴的方法
public String chop();
}
2. 新建2个实现类,Chinese类,StoneAxe类。
Chinese类:
package springtest;
//Chinese实现Person接口
public class Chineseimplements Person {
//面向Axe接口编程,而不是具体的实现累
private Axe axe;
//默认的构造器
public Chinese(){}
public void setAxe(Axe axe){
this.axe=axe;
}
//实现Person接口的useAxe方法
public void useAxe() {
System.out.println(axe.chop());
}
}
StoneAxe类:
package springtest;
public class StoneAxeimplements Axe {
//默认构造器
public StoneAxe(){}
//实现Axe接口的chop方法
public String chop() {
return "斧头砍柴好慢";
}
}
3. 下面是spring配置:
<?xml version="1.0" encoding="UTF-8"?>
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<bean id="chinese" class="springtest.Chinese">
<property name="axe">
<ref local="stoneAxe"/>
</property>
</bean>
<bean id="stoneAxe" class="springtest.StoneAxe"/>
</beans>
4. 新建一个测试类:BeanTest:
package springtest;
import org.springframework.context.ApplicationContext;
importorg.springframework.context.support.FileSystemXmlApplicationContext;
public class BeanTest {
public static void main(String[] args) {
ApplicationContext ctx=new FileSystemXmlApplicationContext("D:/myEclipse/workspace2/ssh/WebRoot/WEB-INF/applicationContext.xml");
Person p=(Person)ctx.getBean("chinese");
p.useAxe();
}
}
控制台打印结果:
log4j:WARN No appenders could befound for logger(org.springframework.context.support.FileSystemXmlApplicationContext).
log4j:WARN Please initialize thelog4j system properly.
斧头砍柴好慢