依賴注入綜合示例

案例:通過不同的紙張和不同類型墨盒的組合,來裝配出一臺打印機。

架構目錄:


步驟一:在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);

   }

發佈了31 篇原創文章 · 獲贊 0 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章