如何配置IntelliJ/gradle以使用dagger 2.0

Mar*_*nik 26 java gradle dagger-2

我有一个gradle项目,我想在其中使用dagger 2.0.我不知道如何配置IntelliJ和gradle来生成文件并让IntelliJ找到它们?

我的build.gradle文件如下所示:

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

version = '1.0'

repositories {
    mavenCentral()
    maven {
        url "https://oss.sonatype.org/content/repositories/snapshots"
    }
}

dependencies {
    compile 'org.slf4j:slf4j-api:1.7.12'
    compile 'org.slf4j:slf4j-simple:1.7.12'
    compile 'commons-configuration:commons-configuration:1.10'
    compile 'commons-collections:commons-collections:3.2.1'
    compile 'com.google.dagger:dagger:2.0'
    compile 'com.google.dagger:dagger-compiler:2.0:jar-with-dependencies'
    compile 'com.pi4j:pi4j-distribution:1.1-SNAPSHOT'
}
Run Code Online (Sandbox Code Playgroud)

在我的应用程序的构建目录中,文件DaggerXmlConfigurationComponent存在,这是Dagger创建的组件.但我无法在IntelliJ中使用它,因为它找不到类.

这不是Android应用程序,而是Raspberry Pi的应用程序.

rob*_*lco 16

您必须手动为IntelliJ启用注释处理:在设置...→构建,执行,部署→编译器→注释处理器中,选中启用注释处理并从项目类路径获取处理器.


小智 8

我找到了解决方案.

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'
}
Run Code Online (Sandbox Code Playgroud)

此外,如果您使用的是Intellij,建议采用以下配置:

但是,在IntelliJ IDEA中使用Gradle集成时,您需要手动启用注释处理,而不是构思任务:在设置...→构建,执行,部署→编译器→注释处理器中,选中启用注释处理并从项目中获取处理器类路径.要模仿Gradle行为和生成的文件行为,您可以将生产和测试源目录分别配置为build/generated/source/apt/main和build/generated/source/apt/test,并选择相对于以下方式存储生成的源:Module内容根.我还必须从整个构建目录中删除Exclude并将生成的/ source/apt/main目录标记为源.

  • 在我添加了“ idea”插件之前,它对我来说没有效果。即使没有启用注释处理器,它也可以工作。`apply plugin:'idea'` (3认同)

TmT*_*ron 5

我知道的最简单的方法是使用apt-idea 插件

只需激活build.gradle文件中的插件:

plugins {
    id 'java'
    id 'net.ltgt.apt-idea' version "0.15"
}
Run Code Online (Sandbox Code Playgroud)

然后将注释处理器添加到annotationProcessor配置中:

final DAGGER_VER = '2.16'
dependencies {
    implementation "com.google.dagger:dagger:${DAGGER_VER}"
    annotationProcessor"com.google.dagger:dagger-compiler:${DAGGER_VER}"
}
Run Code Online (Sandbox Code Playgroud)

我在 GitHub 上创建了一个非常简单的测试项目:ex.dagger
(使用 IntelliJ 2018.1.4,Gradle 4.7)