![](/img/trans.png)
[英]Use Dagger2 in android library project throws `NoClassDefFoundError` at runtime
[英]Use Dagger2 without Android
我想在项目 Gradle 中使用 Dagger2 和 MVP,但没有 Android,在本机 Java 中。 但是我无法构建我的项目,从未生成 DaggerAppComponent 类。 此类由 Dagger 库在编译时自动生成。
构建.gradle:
plugins {
id "net.ltgt.apt" version "0.11"
}
apply plugin: 'java'
apply plugin: 'idea'
sourceCompatibility = 1.8
repositories {
mavenCentral()
}
compileJava {
options.annotationProcessorPath = configurations.apt
}
configurations {
apt
}
dependencies {
testCompile group: 'junit', name: 'junit', version: '4.12'
compile "com.google.dagger:dagger:2.11"
apt "com.google.dagger:dagger-compiler:2.11"
apt "com.google.dagger:dagger-producers:2.11"
compileOnly "com.google.auto.factory:auto-factory:1.0-beta3"
apt "com.google.auto.factory:auto-factory:1.0-beta3"
compileOnly "org.immutables:value:2.2.10:annotations"
apt "org.immutables:value:2.2.10"
provided 'javax.annotation:jsr250-api:1.0'
compile 'org.glassfish:javax.annotation:10.0-b28'
}
主程序
public class Main {
private static AppComponent appComponent;
public static void main(String[] args) {
/**
* Launch the application.
*/
EventQueue.invokeLater(new Runnable() {
public void run() {
appComponent = initDagger();
try {
MainViewImpl mainView = new MainViewImpl();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public AppComponent getAppComponent() {
return appComponent;
}
public static AppComponent initDagger() {
return DaggerAppComponent.builder().appModule(new AppModule())
.build();
}
}
当我构建我的项目时,我有这个错误:
Error:(38, 16) java: cannot find symbol
symbol: variable DaggerAppComponent
location: class main.Main
DaggerAppComponent 类永远不会构建。 你有想法吗 ?
您需要遵循 Gradle Annotation Processing 插件的 IDE 说明https://github.com/tbroyer/gradle-apt-plugin
像 Dagger2 和 Lombok 这样的注释需要一个注释处理器。 这可以通过配置 IDE 来完成,但最好让 gradle 尽可能多地处理。
话虽如此,您仍然需要为 Eclipse 或 IntelliJ 做一些事情。 对于 IntelliJ,这是重要的部分:
在 IntelliJ IDEA 中使用 Gradle 集成(而不是 ida 任务)时,建议从 IDEA 2016.3 开始将 IDE 构建操作委托给 Gradle 本身: https ://www.jetbrains.com/idea/whatsnew/#v2016- 3-gradle否则,您必须手动启用注释处理:在Settings... → Build, Execution, Deployment → Compiler → Annotation Processors 中,选中 Enable annotation processing 和从项目类路径获取处理器。 要模仿 Gradle 行为和生成的文件行为,您可以将生产和测试源目录分别配置为build/generated/source/apt/main和build/generated/source/apt/test并选择存储生成的源相对于:模块内容根。
在 Launcher 的 Project Defaults 中进行配置,这样您只需执行一次。
请注意,从 IntelliJ IDEA 2016.1 开始,除非您将构建操作委托给 Gradle,否则您必须在导入项目时取消选中 Create separate module per source set 。
我会说这段代码
compileJava {
options.annotationProcessorPath = configurations.apt
}
configurations {
apt
}
没有必要。
您还必须在 IDE 选项中激活注释处理。 您可以通过运行gradle compile
并检查 gradle 是否生成源来检查是否是您的情况
几年前我遇到了类似的问题,我终于解决了。 你可以在这里找到解决方案
例如,如果您想在 Java 库中实现 Dagger2。 我写了一个简短的演示,你会看到如何去做。 看看这个:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.