码迷,mamicode.com
首页 > 其他好文 > 详细

<转>依赖注入的简单描述:

时间:2016-04-21 21:55:41      阅读:115      评论:0      收藏:0      [点我收藏+]

标签:

场景:现在有个磁盘输出的业务,客户端需要通过2个业务对象进行输出。 一个是通过Floppy(软盘),另一个是通过USB接口。

1、 定义一个接口

例如:

package spring.basic.BusinessFactory;  

public interface IDeviceWriter {  

    public void saveToDevice();  

2、 定义实现接口的类(重写接口方法)

例如:(此处定义了两个实现接口的类)

类FloppyWriter:

package spring.basic.BusinessFactory;  

public class FloppyWriter implements IDeviceWriter {  

    public void saveToDevice() {  

        System.out.println("储存至软盘…");  

    }  

类UsbDiskWriter:

package spring.basic.BusinessFactory;

public class UsbDiskWriter implements IDeviceWriter {

public void saveToDevice() {

     System.out.println("储存至移动硬盘…");

}

}

3、 定义业务类(指定该类的功能)

package spring.basic.BusinessFactory;

public class BusinessBean {

private IDeviceWriter writer;

public void setDeviceWriter(IDeviceWriter writer) {

     this.writer = writer;

}

public IDeviceWriter getDeviceWriter() {

     return writer;

}

public void save() {

     if (writer == null) {

         throw new RuntimeException("DeviceWriter needed...");

     }

     writer.saveToDevice();

}

}

4、 定义配置文件(将实现接口的类和业务类写入配置文件中)

例如:

<?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="floppy" class="spring.basic.BusinessFactory.FloppyWriter"/> 

    <bean id="usb" class="spring.basic.BusinessFactory.UsbDiskWriter"/> 

    <bean id="businessBean"   

          class="spring.basic.BusinessFactory.BusinessBean">   

        <property name="deviceWriter"> 

            <ref bean="floppy"/> 

        </property>   

    </bean>   

</beans>

5、 定义客户端代码

package spring.basic.BusinessFactory;  

import org.springframework.context.ApplicationContext;  

import org.springframework.context.support.ClassPathXmlApplicationContext;  

public class SpringDemo {  

    public static void main(String[] args) {  

        ApplicationContext context = new ClassPathXmlApplicationContext(  

        "businessFactoryConfig.xml");  

        BusinessBean business = (BusinessBean) context.getBean("businessBean");  

        business.save();  

    }  

}  

<转>依赖注入的简单描述:

标签:

原文地址:http://www.cnblogs.com/DoveZoe/p/5418784.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!