如何配置dagger + gradle

Nec*_*net 18 android gradle dagger

我有一个项目并迁移到gradle依赖,但我发现自己有一个问题试图用gradle设置dagger,我第一次编译它工作完美(或者如果我清理)但如果我尝试两次然后它给我错误像:

错误:(13,14)错误:重复类:com.myapp.android.application.InjectingApplication $ InjectingApplicationModule $$ ModuleAdapter

我尝试使用android-apt插件并在文档中配置,但我仍然得到相同的错误(https://bitbucket.org/hvisser/android-apt/overview)

我也尝试使用提供的依赖,就像编译本教程(https://github.com/frankdu/android-gradle-dagger-tutorial)但到目前为止没有运气.

你有任何想法如何配置匕首和gradle?

编辑

我的build.gradle看起来像这样

apply plugin: 'android'
apply plugin: 'android-apt'

android {
    compileSdkVersion 19
    buildToolsVersion "19.0.2"

    defaultConfig {
        minSdkVersion 9
        targetSdkVersion 19
        packageName "com.myapp.android"

    }

    buildTypes {
        release {
            runProguard false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
        }
    }
}


dependencies {
    compile project(':volley')
    apt 'com.squareup.dagger:dagger-compiler:1.2.0'
    compile 'com.squareup.dagger:dagger:1.2.0'
}
Run Code Online (Sandbox Code Playgroud)

而我的顶级build.gradle看起来像这样

// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:0.9.+'
        classpath 'com.neenbedankt.gradle.plugins:android-apt:1.2'
    }
}

allprojects {
    repositories {
        mavenCentral()
    }
}
Run Code Online (Sandbox Code Playgroud)

编辑#2:

我尝试再次提供,因为@Marco建议没有运气,我不知道是否有可能导致此问题的库或gradle版本,我目前正在使用1.10.从好的方面来说,我确实找到了一种方法来使它工作,但我希望通过添加提供的语句来实现.我这样做的方式是旧的方式:

定义apt配置

configurations {
     apt
}
Run Code Online (Sandbox Code Playgroud)

添加Dagger编译器库

apt 'com.squareup.dagger:dagger-compiler:1.2.0'
Run Code Online (Sandbox Code Playgroud)

并实现对applicationVariant的这个钩子,据我所知android-apt做了类似的事情.这有意义吗?为什么?

def getSourceSetName(variant) {
    return new File(variant.dirName).getName();
}

android.applicationVariants.each { variant ->
    def aptOutputDir = project.file("build/source/apt")
    def aptOutput = new File(aptOutputDir, variant.dirName)


    android.sourceSets[getSourceSetName(variant)].java.srcDirs+= aptOutput.getPath()

    variant.javaCompile.options.compilerArgs += [
            '-processorpath', configurations.apt.getAsPath(),
            '-s', aptOutput
    ]

    variant.javaCompile.source = variant.javaCompile.source.filter { p ->
        return !p.getPath().startsWith(aptOutputDir.getPath())
    }

    variant.javaCompile.doFirst {
        aptOutput.mkdirs()
    }
}
Run Code Online (Sandbox Code Playgroud)

Mar*_* RS 17

我在这个示例Volley示例中使用匕首.我没有遇到任何匕首问题,我使用的编译器包括:

provided 'com.squareup.dagger:dagger-compiler:1.2.1'
Run Code Online (Sandbox Code Playgroud)

  • 实际上,这是正确的做法.虽然Hugo Visser的apt插件为编译时生成主要源代码工作,但它无法生成测试源,我得到了"无法加载MyModule类的模块适配器".请确保为此模块运行代码生成.此博客文章提供了更多见解:http://www.sinking.in/blog/provided-scope-in​​-gradle/ (2认同)