Spring反转容器IOC

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();  
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值