在没有 Android 的情况下使用 Dagger2

R.T*_*ier 6 java dependency-injection intellij-idea dagger-2

我想在 Gradle 项目中使用 Dagger2 和 MVP,但不使用 Android,而是使用本机 Java。但我无法构建我的项目,DaggerAppComponent 类永远不会生成。该类由 Dagger lib 在编译时自动生成。

构建.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'

}
Run Code Online (Sandbox Code Playgroud)

主程序.java

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

当我构建项目时出现此错误:

Error:(38, 16) java: cannot find symbol
  symbol:   variable DaggerAppComponent
  location: class main.Main
Run Code Online (Sandbox Code Playgroud)

DaggerAppComponent 类永远不会被构建。你有好主意吗 ?

Nov*_*ata 1

您需要遵循 Gradle 注释处理插件的 IDE 说明https://github.com/tbroyer/gradle-apt-plugin

\n\n

像 Dagger2 和 Lombok 这样的注释需要注释处理器。这可以通过配置 IDE 来完成,但最好尽可能由 gradle 来处理。

\n\n

话虽这么说,您仍然需要为 Eclipse 或 IntelliJ 做一些事情。\n对于 IntelliJ,这是重要的部分:

\n\n
\n

在 IntelliJ IDEA 中使用 Gradle 集成(而不是 ida 任务)时,建议从 IDEA 2016.3 开始将 IDE 构建操作委托给 Gradle 本身:\n https://www.jetbrains.com/idea /whatsnew/#v2016-3-gradle否则,\n 您必须手动启用注释处理:在Settings\xe2\x80\xa6 \xe2\x86\x92\n 构建、执行、部署 \xe2\x86\ 中x92 编译器 \xe2\x86\x92 注释处理器,选中\n 启用注释处理并从项目\n 类路径获取处理器。要模仿 Gradle 行为和生成的文件行为,\n 您可以将生产和测试源目录配置为\n build/ generated/source/apt/mainbuild/ generated/source/apt/test \n 并选择存储生成的源相对于:模块\n 内容根。

\n
\n\n

在启动器的项目默认值中进行配置,这样您只需执行一次。

\n\n
\n

请注意,从 IntelliJ IDEA 2016.1 开始,除非您将构建操作委托给 Gradle,否则您必须在导入项目时取消选中为每个源集创建单独的模块

\n
\n

  • 我已启用:注释处理器中的模块内容根并且它可以工作!谢谢 !!! (2认同)