日期:2014-05-19 浏览次数:20788 次
package org.interfaces; //定义person接口 public interface Person { //接口中定义一个吃食物的方法 public void eatFood(); }
package org.interfaces; //定义Food接口 public interface Food { //在接口中定义一个吃的方法,返回吃东西 public String eat(); }
package org.interfaces.impl; import org.interfaces.Food; import org.interfaces.Person; //person 接口的具体实现类 public class Man implements Person { //定义Food接口私有属性,面向Food接口编程,而不是具体实现类。 private Food food; //构建setter方法 public void setFood(Food food){ this.food=food; } //实现Person接口eatFood方法 public void eatFood(){ System.out.println(food.eat()); } }
package org.interfaces.impl; import org.interfaces.Food; public class Apple implements Food { public String eat(){ return "正在吃苹果……"; } }
package org.interfaces.impl; import org.interfaces.Food; public class Orange implements Food { public String eat(){ return "正在吃橘子……"; } }
<?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.0.xsd"> <!--定义一个bean,该bean的id是man,class指定该bean实例的实现类。 --> <bean id="man" class="org.interfaces.impl.Man"> <property name="food"> <ref local="apple"/> </property> </bean> <!-- 定义apple bean,Food接口的实现类 --> <bean id="apple" class="org.interfaces.impl.Apple"></bean> <bean id="orange" class="org.interfaces.impl.Orange"></bean> </beans>
package org.test; import org.interfaces.Person; import org.springframework.context.ApplicationContext; import org.springframework.context.support.FileSystemXmlApplicationContext; public class Test { public static void main(String[] args) { //创建Application对象,参数为配置文件放置的位置 ApplicationContext context= new FileSystemXmlApplicationContext("config.xml"); //通过Person bean的id来获取bean实例,面向接口编程,因此此处强制类型转换为 //接口类型 Person p=(Person)context.getBean("man"); p.eatFood(); } }
<bean id="man" class="org.interfaces.impl.Man"> <property name="food"> <ref local="orange"/> </property> </bean>