如何在 build.gradle 中新增 Dagger 2

自 Gradle 2.2 釋出以來,不再使用 android-apt 外掛。應使用以下設定 Dagger 2 的方法。對於舊版 Gradle,請使用下面顯示的上一個方法。

對於 Gradle> = 2.2

dependencies {
    // apt command comes from the android-apt plugin
    annotationProcessor 'com.google.dagger:dagger-compiler:2.8'
    compile 'com.google.dagger:dagger:2.8'
    provided 'javax.annotation:jsr250-api:1.0'
}

對於 Gradle <2.2

要使用 Dagger 2,必須新增 android-apt 外掛,將其新增到根 build.gradle:

buildscript {
    dependencies {
        classpath 'com.android.tools.build:gradle:2.1.0'
        classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'
    }
}

然後應用程式模組的 build.gradle 應該包含:

apply plugin: 'com.android.application'
apply plugin: 'com.neenbedankt.android-apt'
    

android {
    …
}

final DAGGER_VERSION = '2.0.2'
dependencies {
    …

    compile "com.google.dagger:dagger:${DAGGER_VERSION}"
    apt "com.google.dagger:dagger-compiler:${DAGGER_VERSION}"
}

參考: https//github.com/codepath/android_guides/wiki/Dependency-Injection-with-Dagger-2