2017-09-06 44 views
1

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

的build.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' 

} 

Main.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(); 
    } 
} 

当我建立我的项目,我有这样的错误:

Error:(38, 16) java: cannot find symbol 
    symbol: variable DaggerAppComponent 
    location: class main.Main 

类DaggerAppComponent永远不会建立。 你有想法吗?

+0

你有没有''导入''班? – f1sh

+0

匕首编译器依赖范围不应该是“compileOnly”吗?我甚至不确定'apt'类型适用于非android项目。 – yegodm

+0

哪些类? 问题是我无法生成类DaggeAppComponent。 认为 –

回答

0

您需要按照IDE的说明的摇篮标注处理插件https://github.com/tbroyer/gradle-apt-plugin

注解像Dagger2和龙目岛需要注释处理器。这可以通过配置IDE来完成,但最好尽可能使用Gradle来处理。

这就是说,仍然有事情你必须做的Eclipse或IntelliJ。 的IntelliJ,这是重要的组成部分:

当IntelliJ IDEA的使用摇篮集成(而不是 IDA任务),建议委托IDE建设行动 摇篮本身出发与IDEA 2016.3: https://www.jetbrains.com/idea/whatsnew/#v2016-3-gradle否则, 你必须手动启用注释处理:在设置...→ 建立,执行,部署→编译器→标注处理,检查 启用注释处理并获得项目 类路径处理器。模仿摇篮行为和生成的文件的行为, 可以配置生产和测试源目录 编译/生成/源/公寓/主构建/生成/源/公寓/分别选择测试 将生成的源相对于:模块 内容根。

在启动程序中的Project Defaults中进行配置,以便您只需执行一次。

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

+2

我已启用:注释处理器中的模块内容根,它的工作! 谢谢! –

0

我要说的是,这个代码

compileJava { 
    options.annotationProcessorPath = configurations.apt 
} 

configurations { 
    apt 
} 

是没有必要的。

您还必须激活IDE选项中的注释处理。您可以通过运行gradle compile来检查是否属于您的情况,并检查gradle是否生成源文件。

几年前,我遇到过类似的问题,最后我终于解决了这个问题。你可以找到解决办法here

+0

启用注解处理并从项目类路径中获取处理器已在我的IDE中启用。我有添加应用'插件:“net.ltgt.apt”'但没有改变。谢谢 –