是否有任何方法可以让IntelliJ IDEA在Java项目中识别Dagger 2生成的类?
上下文
我已经在Java中启动了一个个人项目, Gradle
作为构建系统,我想使用Dagger 2作为DI。 这样做的主要原因是习惯了该库,并能够在更大的项目中轻松使用它。
我试过了什么
我已经设法使用IntelliJ IDEA运行Google示例
问题
IntelliJ IDEA一直告诉我它无法解析生成的类(在本例中为DaggerCoffeeApp_Coffee
)。 不知道编写的代码是否正确(特别是在学习使用Dagger 2时),这有点烦人。
所有java类都与Google示例相同。 这是我的build.gradle
文件:
apply plugin: 'java' repositories { mavenCentral() } dependencies { testCompile group: 'junit', name: 'junit', version: '4.12' compile 'com.google.dagger:dagger:2.0.1' compile 'com.google.dagger:dagger-compiler:2.0.1' }
题
是否有任何方法可以让IntelliJ IDEA将DaggerCoffeeApp_Coffee
识别为生成的类(因此可以通过`ctrl + left click实现它的实现)?
最后我做到了!
我不得不添加apt
和idea
插件,所以我的build.gradle
文件看起来像这样:
buildscript { repositories { maven { url "https://plugins.gradle.org/m2/" } } dependencies { classpath "net.ltgt.gradle:gradle-apt-plugin:0.4" } } apply plugin: "net.ltgt.apt" apply plugin: 'java' apply plugin: 'idea' repositories { mavenCentral() } dependencies { testCompile group: 'junit', name: 'junit', version: '4.12' compile 'com.google.dagger:dagger:2.0.1' apt 'com.google.dagger:dagger-compiler:2.0.1' }
我发现最简单的方法:
-
添加
idea
插件并添加Dagger2依赖项,如下所示:plugins { id "net.ltgt.apt" version "0.10" } apply plugin: 'java' apply plugin: 'idea' sourceCompatibility = 1.8 repositories { mavenCentral() } dependencies { testCompile group: 'junit', name: 'junit', version: '4.12' compile 'com.google.dagger:dagger:2.11' apt 'com.google.dagger:dagger-compiler:2.11' }
-
启用IntelliJ的
Annotation Processing
:转到Settings
并搜索Annotation Processors
,选中启用注释处理,如下图所示:
您必须在IntelliJ中手动启用注释处理 。
来自:设置 – >构建,执行,部署 – >编译器 – >注释处理器 – > 启用注释处理并从项目类路径获取处理器
然后重建项目,您将在项目中找到生成的类。
请注意我在(java) android项目中使用过这个解决方案。
我正在使用IntelliJ IDEA的net.ltgt.apt
版本, net.ltgt.apt
插件版本0.14
和Dagger版本2.14.1
,以及在build.gradle
文件中应用idea
插件(如Pelocho的答案 )我发现我还必须告诉IntelliJ它可以找到Dagger生成的源,如下所示:
apply plugin: 'idea' idea { module { sourceDirs += file("$buildDir/generated/source/apt/main") testSourceDirs += file("$buildDir/generated/source/apt/test") } }
这是适用于我的解决方案:
文件 – >项目结构 – >(在模块列表下选择项目) – >打开“依赖项”选项卡
然后,单击绿色的“+”符号,选择“JAR或目录”并选择“build / classes / main”文件夹。
另一种解决方案是使用build.gradle中的“dependencies”块将文件夹与构建类文件链接:
这是我为了让Idea与Dagger2和gradle一起工作所必须做的。
- 打开注释处理,如上面的答案所示。
-
将以下内容添加到
build.gradle
文件中,以便Idea将生成的类视为源。sourceDirs += file("$projectDir/out/production/classes/generated/")
这是我的build.gradle
的完整列表
plugins { id 'java' id 'idea' id "net.ltgt.apt" version "0.10" } idea { module { sourceDirs += file("$projectDir/out/production/classes/generated/") } } repositories { mavenCentral() } dependencies { compile 'com.google.dagger:dagger:2.16' apt 'com.google.dagger:dagger-compiler:2.16' } sourceCompatibility = 1.8
此外,我必须添加以下gradle任务(到我的build.gradle文件)以清除我的out
目录。 当我移动一些文件并且Dagger2重新生成源文件时, out
目录没有被清除:(。我还在我的运行配置中包含了这个任务,以便在重建我的项目之前触发它。
task clearOutFolder(type: Delete) { delete 'out' }