Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android Dagger 依賴注入框架入門:概念、環境配置與常見規則

編輯:關於 Android 程式設計

第一次接觸 Dagger 這套 Android 依賴注入(DI)框架時,會覺得它跟 Spring 的 IoC 概念很像。但兩者有個關鍵差異:Spring 依靠執行期反射完成注入,而 Dagger 採用編譯期預處理。這個選擇很重要——基於反射的 DI 在行動裝置上非常耗資源,時間與空間都是負擔,而 Dagger 把解析工作提前到編譯階段,執行期幾乎沒有額外成本。

由於目前開發都以 Android Studio 為主,本文先說明環境配置,再逐項拆解核心概念。建議先讀過官方文件:https://square.github.io/dagger/ 。中文翻譯可參考 https://fanxu.me/post/2013-07-18#main ,內容相當詳盡。

Dagger 建立在 Android Annotations 的基礎之上,若對註解處理不熟悉,建議先補這塊知識。

一、在 Android Studio 中配置 Dagger

因為使用 Gradle,配置方式與過去在 Eclipse 直接丟 jar 檔不同:

1. 建立一個 module。
2. 找到該 module 的 build.gradle。
3. 在 dependencies 區塊中加入兩行:

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:19.+'
    compile 'com.squareup.dagger:dagger:1.2.+'
    provided 'com.squareup.dagger:dagger-compiler:1.2.+'
}

注意兩者的 scope 不同:dagger 是執行期需要的函式庫,用 compile;dagger-compiler 是註解處理器,只在編譯期運作,必須用 provided,否則會打包進 APK 造成體積膨脹甚至衝突。

二、為什麼需要 Dagger

任何新工具的出現都有其背景。我們常說「要透過工廠類建立產品類物件」,但實務上真正被關注的是產品類本身,而不是工廠類、更不是它的生產過程。工廠程式碼寫多了,就成了純粹為了滿足語法而存在的負擔。

Dagger 的目標就是簡化這部分代碼,讓你把注意力放回真正需要關注的類別上。

三、核心概念

1. @Inject:標記需要被注入的依賴

public class ClassRoom {
    @Inject Student student1;   // @Inject 表示這個欄位由 Dagger 提供
    // 若沒有提供對應方法,編譯時會報錯
}

但光有 @Inject 還不夠——Dagger 需要知道 Student 物件該怎麼產生出來。這就是 @Module 與 @Provides 的用途。

2. @Module 與 @Provides:提供物件實例

// @Module 表示這是一個提供依賴的模組
@Module
public class StudentModule {

    // @Provides 表示這個方法能供應某型別的物件
    @Provides
    Student provideStudent() {
        return new Student();
    }
}

注意:@Provides 方法由 Dagger 在需要時呼叫,而非由我們自己呼叫。這與傳統工廠模式的心智模型不同,也是初學者最容易卡住的地方。

3. ObjectGraph:把模組串起來

ObjectGraph og = new ObjectGraphBuilder()
        .plus(new EveModule(), new BabyModule(), new ToddlerModule(), new SchoolAgeChildModule())
        .build();

ObjectGraph 扮演圖(Graph)的角色,Dagger 會分析所有模組提供的依賴關係,找出對應的 @Provides 方法,完成注入。

4. @Lazy:延遲初始化

public class ClassRoom {
    @Inject @Lazy Student lazyStudent;

    public void study() {
        lazyStudent.get();   // 呼叫 get() 時才真正建立物件
    }
}

這個註解等同 C 語言裡的宏定義那種「延後展開」的概念——宣告時不建立,第一次用到時才建立。

5. @Singleton:單例範圍

加上 @Singleton 後,同一個 ObjectGraph 內重複注入時會得到同一個實例,不會重複呼叫 @Provides 方法。

6. @Qualifier:限定符

有些時候,單純的型別不足以指定依賴。例如一個類別需要兩個 Student,但分別要是不同的人。這時可以用限定符註解。這類註解本身帶有 @Qualifier 標記。

下面是 javax.inject 中 @Named 的宣告:

@Qualifier
@Retention(RUNTIME)
public @interface Named {
    String value() default "";
}

使用方式:

public class ClassRoom {

    @Inject @Named("胖虎") Student pangHu;

    @Inject @Named("李四") Student liSi;
    // 這樣就限定了所要獲取的 Student 物件實例的性質
}

對應的提供方法也要加上相同的限定符:

@Module
public class StudentModule {

    @Provides @Named("胖虎") Student providePangHuStudent() {
        return new Student("胖虎");
    }

    @Provides @Named("李四") Student provideLiSiStudent() {
        return new Student("李四");
    }
}

依賴關係也可以同時帶有多重限定符註解。

7. 靜態注入(Static Injections)

官方建議謹慎使用這個特性,因為靜態依賴注入很難測試和複用。Dagger 可以注入靜態變數,擁有 @Inject 靜態變數的類別必須在 @Module 的 staticInjections 中明確說明。

@Module(staticInjections = LegacyCoffeeUtils.class)
class LegacyModule { }

接著用 ObjectGraph.injectStatics() 注入:

ObjectGraph objectGraph = ObjectGraph.create(new LegacyModule());
objectGraph.injectStatics();

8. 編譯期有效性檢查

Dagger 內含一個註解處理器,會在編譯時檢查模組與注入的有效性。這個處理器相當嚴格:只要有任何綁定是無效或不完整的,就會直接引發編譯錯誤。這正是 Dagger 相對執行期反射方案的優勢——問題在編譯階段就暴露,而不是等到線上崩潰。

看個官方例子:

@Module
public class DripCoffeeModule {

    @Provides
    Heater provideHeater(Executor executor) {
        return new CpuHeater(executor);
    }
}

問題在哪裡?provideHeater 是由 Dagger 呼叫的,而它的參數 executor 必須由某個 @Provides 方法提供。但我們不能對這個參數加 @Inject,那要怎麼讓 Dagger 知道去哪裡找?

有兩種解法:

一、把 provideExecutor() 方法放進同一個 Module,Dagger 就能找到並注入這個參數。

二、在 @Module 加上 complete=false,標記這是一個不完整的 Module(不完整的 Module 允許缺少物件實例):

@Module(complete=false)
public class DripCoffeeModule {

    @Provides
    Heater provideHeater(Executor executor) {
        return new CpuHeater(executor);
    }
}

9. injects 參數與 library 標記

若在 @Module 中加入 injects(注入物件清單綁定),而這個 Module 提供的物件可能被清單以外的類別使用,就應該把該 Module 標記為 library 以避免出錯:

@Module(
    injects = ClassRoom.class,
    library = true
)
public class StudentModule {

    @Provides Student provideStudent() {
        return new Student();
    }

    @Provides Others provideOthers() {
        return new Others();
    }
}

因為 ClassRoom 只用到 Student,而 injects 清單中也只寫了 ClassRoom.class,那麼 provideOthers() 有可能被 ClassRoom 以外的類別使用,加上 library = true 就能免除報錯。

10. 把 @Provides 集中管理

Dagger 規定所有 @Provides 要放在一個 @Module 中。實務上有兩種做法:用 includes 參數把其他 Module 包含進來,或者(更建議)再建一個空的 Module 作為總入口:

@Module(includes = { StudentModule.class, ExecutorModule.class })
public class AppModules { }

第二種做法的好處是專案長大時,只要改這一個檔案的 includes 清單,不必動任何既有 Module。

11. Module 重載(overrides)

若同一個依賴關係有多個 @Provides 函式,Dagger 會報錯。但測試與開發環境確實有替換正式實作的需求,此時可用 overrides = true 重載綁定關係。

以下 JUnit 測試利用 Mockito 重載了 DripCoffeeModule 的 Heater 綁定:

public class CoffeeMakerTest {

    @Inject CoffeeMaker coffeeMaker;
    @Inject Heater heater;

    @Before
    public void setUp() {
        ObjectGraph.create(new TestModule()).inject(this);
    }

    @Module(
        includes = DripCoffeeModule.class,
        injects = CoffeeMakerTest.class,
        overrides = true
    )
    static class TestModule {
        @Provides @Singleton Heater provideHeater() {
            return Mockito.mock(Heater.class);
        }
    }

    @Test
    public void testHeaterIsTurnedOnAndThenOff() {
        Mockito.when(heater.isHot()).thenReturn(true);
        coffeeMaker.brew();
        Mockito.verify(heater, Mockito.times(1)).on();
        Mockito.verify(heater, Mockito.times(1)).off();
    }
}

這個 mock 物件會被注入到 CoffeeMaker 中。同樣的思路也很適合程式的小型變體,例如付費版與免費版的差異實作。

學習建議

Dagger 的學習曲線主要不在語法,而在心智模型的轉換:你要接受「物件不是自己 new 出來的,而是宣告需求後由框架供應」這件事。一旦理解 @Inject 是「我要什麼」、@Provides 是「這裡有什麼」、ObjectGraph 是「怎麼把它們接起來」,剩下的都是細節規則。

補充一句:本文示範的是 Dagger 1.x 的 API。後續的 Dagger 2 移除了 ObjectGraph,改以 @Component 取代,並在 Android 生態中廣泛搭配 Dagger Android 使用。若你在新專案中導入,建議直接參考 2.x 的文件,但上述的 DI 核心概念與編譯期檢查優勢是完全通用的。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved