含有接口的spring注入

2 篇文章 0 订阅
2 篇文章 0 订阅

牛刀小试

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如附件

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值