依赖注入综合示例

案例:通过不同的纸张和不同类型墨盒的组合,来装配出一台打印机。

架构目录:


步骤一:在ink包下创建Ink接口和其实现类

Ink接口

public interface Ink {

   public String getColor();

}

实现类ColorInk

public class ColorInk implements  Ink {

   public String getColor() {

      return "彩色墨盒";

   }

}

实现类GrayInk

public class GrayInk implements Ink{

   // 打印采用灰色

      public String getColor() {

        return "灰色墨盒";

      }

}

步骤二:在paper包下创建Paper接口及其实现类

Paper接口

public interface Paper {

  public String getContent();

}

Paper实现类

public class A4Paper implements Paper {

   public String getContent() {

      return  "一张淡定的A4纸";

   }

}

步骤三:在printer包下创建Print类

public class Print {

    private Ink ink;

   private Paper paper;

    public void print(){

      System.out.println("用X颜色的墨盒在纸上打印内容");

    }

  

   public Ink getInk() {

      return ink;

   }

 

   public void setInk(Ink ink) {

      this.ink = ink;

   }

 

   public Paper getPaper() {

      return paper;

   }

 

   public void setPaper(Paper paper) {

      this.paper = paper;

   }

}

步骤四:在applicationContext.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/beanshttp://www.springframework.org/schema/beans/spring-beans.xsd">

  <bean id="colorInk" class="cn.happy.ink.ColorInk"/>

  <bean id="grayInk" class="cn.happy.ink.GrayInk"/>

  <!--对Paper的初始化 -->

  <bean id="paper" class="cn.happy.paper.A4Paper"/>

    <!-- 对打印机进行配置-->

    <bean id="printer"class="cn.happy.printer.Print">

       <property name="ink" ref="colorInk"></property>

       <property name="paper" ref="paper"></property>  

    </bean>

</beans>

步骤五:通过Test类测试

public static void main(String[] args) {

 

      ApplicationContextcontext = new ClassPathXmlApplicationContext("applicationContext.xml");

      Printprinter = (Print)context.getBean("printer");

      Stringcolor=printer.getInk().getColor();

      Stringcontent=printer.getPaper().getContent();

      System.out.println(color);

      System.out.println("===========");

      System.out.println(content);

   }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值