Spring学习笔记2--反向控制(IoC)的例子

反向控制也叫依赖注入,使用IoC,对象的依赖都是在对象创建时由负责协调系统中各个对象的外部实体提供的,所以IoC意味着关于对象如何得到它的协作对象责任的反转了。

下面是我编写的例子:

1:先写一个接口

package com.spring.study.ioctest; /** * 寻找接口 * @author shy.qiu */ public interface Quest { // 执行方法 public abstract Object doQuest(); }

2:此接口的实现类

package com.spring.study.ioctest; /** * 创建一个实现Quest接口的类--宝藏寻找 * @author shy.qiu * */ public class TreasureQuest implements Quest{ public TreasureQuest() {}; // 实现接口方法 public Object doQuest() { // 得到一个宝藏 return new Treasure(); } }

上面的类要用到的一个类:

package com.spring.study.ioctest; /** * 宝藏类 * @author shy.qiu * */ public class Treasure { public Treasure () { System.out.println("寻找到了宝藏!"); } }

3:编写另一个接口:

package com.spring.study.ioctest; /** * 猎人接口 * @author shy.qiu */ public interface Hunters { // 执行任务 public Object doTask(); }

4:此接口的实现类

package com.spring.study.ioctest; /** * 实现猎人接口的类 * @author shy.qiu */ public class HunterMan implements Hunters { public HunterMan(String name){ this.name=name; }; // 姓名 private String name; // 什么任务 private Quest quest; // 执行 public Object doTask() { return quest.doQuest(); } // 给猎人分配任务 public void setQuest(Quest quest) { this.quest = quest; } }

5:配置文件的编写hunterQuest.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.0.xsd"> <!-- 定义一个任务:宝藏寻找 --> <bean id="quest" class="com.spring.study.ioctest.TreasureQuest"> </bean> <!-- 定義一个猎人 --> <bean id="hunter" class="com.spring.study.ioctest.HunterMan"> <constructor-arg> <value>Cheng Long</value><!-- 指定名字 --> </constructor-arg> <property name="quest"> <ref bean="quest"/><!-- 给他分配一个任务 --> </property> </bean> </beans>

6:编写运行代码

package com.spring.study.ioctest; import java.io.FileNotFoundException; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class TaskApp { public static void main(String[] args) throws BeansException, FileNotFoundException { // 载入配置文件 ApplicationContext factory = new ClassPathXmlApplicationContext( "hunterQuest.xml"); // 从工厂中获得 HunterMan HunterMan hunterMan = (HunterMan) factory.getBean("hunter"); // 执行任务 hunterMan.doTask(); } }

这样一个简单的IoC程序就完成了。

这个HunterMan类和以往的程序不一样的地方在于,城市猎人不知道会接受那种任务,只有配置文件知道他要去做什么任务,

重要的是这种把对象的责任从对象自身中转移出来的思想。

:和上一篇一样,使用了看似没有必要的接口。但是把具体的实现隐藏在接口的下面是减小程序耦合性的通常做法。现在不是提倡面向接口编程吗?

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值