牛刀小试
1.定义一接口animal 功能 吃食物
public interface Animal {
//动物吃食物
public void eat(Food foot);
}
2.定义food 得到食物的名字
public interface Food {
//什么食物
public String getName();
}
3.定义一class feeder 饲养员给动物喂食物 代码你懂的
public class Feeder {
private Animal animal;
private Food food;
public void setAnimal(Animal animal) {
this.animal = animal;
}
public void setFood(Food food) {
this.food = food;
}
public void feed(){
animal.eat(food);
}
}
3.测试的Test
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test {
public static void main(String[] args) {
//加载applicationcontext.xml 也就是初始化里面的bean
ApplicationContext ctx=new ClassPathXmlApplicationContext("/ApplicationContext.xml");
Feeder fd=(Feeder) ctx.getBean("feeder");
fd.feed();
}
}
4.实现feed
public class ManMeet implements Food{
@Override
public String getName() {
// TODO Auto-generated method stub
return "肉";
}
}
5.实现animal
public class Tiger implements Animal{
@Override
public void eat(Food food) {
System.out.println("老虎吃"+food.getName());
}
}
6.Spring 的 配置如applcationcontext.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 id="anmal" class="com.fit.impl.Tiger"/>
<bean id="foods" class="com.fit.impl.ManMeet"/>
<bean id="feeder" class="com.fit.Feeder">
<property name="animal" ref="anmal"/>
<property name="food" ref="foods"/>
</bean>
</beans>
7.运行Test如附件