您的位置:首页 > 编程语言 > Java开发

Spring反转容器IOC

2008-05-16 13:05 232 查看
IOC中有句著名的格言"don`t call me,i'll call you".
我们传统产生实现的方式需要用new运算符产生类实例.这样类与类之间的偶合性就比较强,不易于软件在将来的升级和维护.反转容器可以消除这样的依赖.
举个简单的例子:
Human.java

package com.wish.IOC;
public interface Human {
public void eat();
public void walk();
}

Chinese.java

package com.wish.IOC;
public class Chinese implements Human{
public void eat() {
  System.out.println("中国以大米为主食");  
}
public void walk() {
  System.out.println("中国人以自行车为交通工具");  
}
}

American.java

package com.wish.IOC;
public class American implements Human{
public void eat() {
  System.out.println("美国人以面包为主食");  
}
public void walk() {
  System.out.println("美国人以汽车为主要交通工具,所以四肢有退化现象");  
}
}

bean.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
"http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
<bean id="chinese" class="com.wish.IOC.Chinese"></bean>
<bean id="american" class="com.wish.IOC.American"></bean></beans>

下面给出测试
IOCTest.java

package com.wish.IOC;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
public class IOCTest {
public static void main(String[] args) {
  ApplicationContext ctx = new FileSystemXmlApplicationContext("/config/bean.xml");  
  Chinese chinese = (Chinese) ctx.getBean("chinese");
  American american = (American) ctx.getBean("american");
  chinese.eat();
  chinese.walk();
  american.eat();
  american.walk();  
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息