Dagger 2.0 - AppEngine - gradle configuration

2019-02-19 07:46发布

问题:

I am trying to move from Dagger 1.2.2 to Dagger 2.0.1 in AppEngine project (NOT Android one).

With Dagger 1.2.2 simple:

compile 'com.squareup.dagger:dagger-compiler:1.2.2'
compile 'com.squareup.dagger:dagger:1.2.2'

did the trick.

With Dagger 2.0.1:

compile 'com.google.dagger:dagger-compiler:2.0.1'
compile 'com.google.dagger:dagger:2.0.1'

does not work (source is generated but mixed up with *.class files in build/classes/main/..package../).

回答1:

You can also do it without net.ltgt.apt plugin, (which by the way may conflict with lombok).

apply plugin: 'java'
apply plugin: 'idea'

def generatedMain = new File(buildDir, "generated/main")

compileJava {
    doFirst {
        generatedMain.mkdirs()
    }
    options.compilerArgs += ['-s', generatedMain]
}
idea.module.sourceDirs += generatedMain

dependencies {
    compileOnly 'com.google.dagger:dagger-compiler:2.8'
    compile 'com.google.dagger:dagger:2.8'
}


回答2:

I've found a solution.

https://github.com/tbroyer/gradle-apt-plugin

buildscript {
  repositories {
    maven {
      url "https://plugins.gradle.org/m2/"
    }
  }
  dependencies {
    classpath "net.ltgt.gradle:gradle-apt-plugin:0.3"
  }
}

apply plugin: "net.ltgt.apt"

dependecies {
  apt 'com.google.dagger:dagger-compiler:2.0.1'
  compile 'com.google.dagger:dagger:2.0.1'
}

Additionally if you are using Intellij a following configuration is recommended:

When using the Gradle integration in IntelliJ IDEA however, rather than the idea task, you'll have to manually enable annotation processing: in Settings… → Build, Execution, Deployment → Compiler → Annotation Processors, check Enable annotation processing and Obtain processors from project classpath. To mimic the Gradle behavior and generated files behavior, you can configure the production and test sources directories to build/generated/source/apt/main and build/generated/source/apt/test respectively and choose to Store generated sources relative to: Module content root.

I've also had to remove Exclude from whole build directory and mark generated/source/apt/main directory as source.