Spring: A Developer's Notebook筆記和小結(4)

/**
作者:Willpower
來源:Rifoo Technology(http://www.rifoo.com)
時間:2005-12-29
備註:轉載請保留以上聲明
**/

本篇主要介紹使用Spring來進行依賴注入,以及對以前代碼的改進。

如果你機器上沒有安裝Spring,需要先到官方網站(
http://www.springframework.org)上去下載,將Spring的lib放到war/WEB-INF/lib下,讓應用能夠找到它們。

將現有應用程序轉移到一個設計良好的POJO的基於Spring的應用其實很簡單,只需要以下幾個步驟:

1 利用依賴注入的思想對現有代碼進行重構。model對象看作bean,service看作aspect。一般我們只有bean,而沒有使用到service。

2 去掉代碼中實例化對象和設置依賴(即通過set方法設置)的那部分代碼。

3 創建一個配置文件來描述bean和aspect。

4 通過Spring來訪問我們的代碼。


下面我們就按照上面的步驟來改進我們的程序:


先看看管理我們bean和aspect的配置文件,目前這裏沒有用到aspect。

Example 1-9. RentABike-context.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="rentaBike" class="ArrayListRentABike">
    <property name="storeName"><value>"Bruce's Bikes"</value></property>
  </bean>

  <bean id="commandLineView" class="CommandLineView">
    <property name="rentaBike"><ref bean="rentaBike"/></property>
  </bean>

</beans>



這裏的<bean id="rentaBike" class="ArrayListRentABike">,後面的class是具體類,實際情況可能需要完整的包名+類名的形式,這裏使用的默認包。而bean前面的id用來唯一標示這個bean。
下面的<property name="storeName"><value>"Bruce's Bikes"</value></property>是給這個bean設置屬性,這裏就是所謂依賴注入的思想。屬性名和值可以被動態的set到相應的bean中去。下面這個commandLineView也一樣,只不過<ref bean="rentaBike"/>表示它有個屬性是rentaBike bean的一個引用。大家如果不明白,後面會講到具體的實現。

接着來看看這個改進後的裝配器:

Example 1-10. RentABikeAssembler.java
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class RentABikeAssembler {
  public static final void main(String[] args) {
    //使用這一句來讀取上面定義的配置文件
    ClassPathXmlApplicationContext ctx = new
      ClassPathXmlApplicationContext("RentABikeApp-context.xml");
    //完成依賴注入
    CommandLineView clv =
      (CommandLineView)ctx.getBean("commandLineView");
    clv.printAllBikes( );
  }
}


它使用ClassPathXmlApplicationContext("RentABikeApp-context.xml")來讀取配置文件,Spring其實有很多方法來讀取配置文件,後面會陸續介紹的。
ctx.getBean("commandLineView");這一句先到配置文件中去找id爲commandLineView的bean,這個時候找到了其具體類是CommandLineView,並將屬性和值注入到這個對象中。

我們回顧一下改動前的代碼:
public class RentABikeAssembler {
  public static final void main(String[] args) {
    CommandLineView clv = new CommandLineView( );//1
    RentABike rentaBike = new ArrayListRentABike("Bruce's Bikes");//2
    clv.setRentaBike(rentaBike);//3
    clv.printAllBikes( );
  }
}


大家可以發現上面我註釋的3句是被替換掉了,這些操作是由Spring框架來完成了依賴注入。
依賴注入的好處就是可以通過修改配置文件來給類動態加載相關的屬性和引用,而不用修改代碼。
發佈了84 篇原創文章 · 獲贊 2 · 訪問量 16萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章