Dagger2和Kotlin运行失败的原因是:app:compileDebugKotlinAfterJava
我试图在测试应用程序中实施Dagger 2,以Kotlin语言学习清洁架构和依赖注入。
编辑:
我可以编译感谢@Logain,但我一直在我的单身(见我的TaskWorker下面)的匕首静态成员问题,所以我在找我该如何解决这个错误
但是,我得到了一个问题,我的DaggerComponent是很好地生成,当我重建 ,但不是当我想运行我的应用程序进行测试,它失败并消失。 它失败,出现这个错误:
错误:(21,29)未解决的引用:DaggerInjectorComponent
错误:执行任务':app:compileDebugKotlinAfterJava'失败。
>编译错误。 查看日志了解更多详情
而当我做一个重建,这个任务正确传递
:app:compileDebugKotlinAfterJava
所以我不明白为什么失败。
这是我的InjectorComponent :
@Singleton @Component(modules = arrayOf(ContextDaggerModule::class, LocalStoreDaggerModule::class)) interface InjectorComponent { fun inject(realmLocalStore: RealmLocalStore) fun inject(taskWorker: TaskWorker) }
ContectDaggerModule :
@Module class ContextDaggerModule (val app: Application) { @Provides @Singleton fun provideContext(): Context = app @Provides @Singleton fun provideApplication(): Application = app @Provides @Singleton fun provideResources(): Resources = app.resources }
LocalStoreDaggerModule :
@Module class LocalStoreDaggerModule { @Provides @Singleton fun provideLocalStore(context: Context): LocalStore { return RealmLocalStore(context) } }
我认为这个问题是由于我在对象声明中注入依赖而引起的,但是所有的元素都是静态的,而Dagger并不欣赏它。 所以,我尝试用一个简单的重写getter和注入数据来破解它,但是nop。
这是我的“黑客”:
object TaskWorker { // @Inject lateinit var localStore: LocalStore // Not work cause it's a static variable var localStore: LocalStore? = null @Inject get() = localStore // some cool function }
我遵循这个代码和本教程
我使用这些依赖关系:
// Dagger2 compile 'com.google.dagger:dagger:2.11' kapt 'com.google.dagger:dagger-compiler:2.11' provided 'org.glassfish:javax.annotation:10.0-b28'
确保您使用的是:
kapt { generateStubs = true }
由于对kapt的一些限制
或者试试:
annotationProcessor 'com.google.dagger:dagger-compiler:2.11'
你不需要这个。
kapt { generateStubs = true }
只需应用插件:
apply plugin: 'kotlin-kapt'
并添加依赖关系:
compile androidDependencies.dagger2 compile androidDependencies.dagger2Android kapt androidDependencies.dagger2Kapt
有时候这些任务会失败,像这样的错误。 尝试clean
并作为最后手段使用invalidate and restart
。 大多数时候它的工作。