Kotlin + Dagger 2:Dagger *文件不会生成
我第一次开始使用Kotlin和Dagger 2。 我认为所有东西都和Java一样,但显然不是。 匕首不会为我生成Dagger *文件。 这是我的代码:
组件:
@PerActivity @Subcomponent(modules = arrayOf(ApplicationModule::class)) interface ActivityComponent { fun inject(app: OneAccountApplication) }
@Singleton @Component(modules = arrayOf(ApplicationModule::class)) interface ApplicationComponent { fun inject(syncService: SyncService) @ApplicationContext fun context(): Context fun application(): Application fun ribotsService(): OneAccountService fun preferencesHelper(): PreferencesHelper fun databaseHelper(): DatabaseHelper fun dataManager(): DataManager }
@ConfigPersistent @Component(dependencies = arrayOf(ApplicationComponent::class)) interface ConfigPersistentComponent { fun activityComponent(activityModule: ActivityModule): ActivityComponent }
模块:
@Module class ActivityModule(private val mActivity: Activity) { @Provides internal fun provideActivity() = mActivity @Provides @ActivityContext internal fun providesContext() = mActivity }
@Module class ApplicationModule(val mApplication: Application) { @Provides @Singleton internal fun provideApplication() = mApplication @Provides @ApplicationContext internal fun provideContext() = mApplication @Provides @Singleton internal fun provideOneAccountService() = OneAccountService.Creator.newOneAccountService() }
范围注释:
@Qualifier @Retention(AnnotationRetention.RUNTIME) annotation class ActivityContext
@Qualifier @Retention(AnnotationRetention.RUNTIME) annotation class ApplicationContext
@Scope @Retention(AnnotationRetention.RUNTIME) annotation class ConfigPersistent
@Scope @Retention(AnnotationRetention.RUNTIME) annotation class PerActivity
这基本上是我的整个DI系统,我成功地使用了我的Java代码。 但是,与Kotlin,由于某种原因,它不起作用。 我还添加了: apply plugin: 'kotlin-kapt'
到gradle.build
例如:
apply plugin: 'com.android.application' apply plugin: 'kotlin-android' apply plugin: 'kotlin-kapt'
在依赖关系中我有:
dependencies { final DAGGER_VERSION = '2.8' def daggerCompiler = "com.google.dagger:dagger-compiler:$DAGGER_VERSION" annotationProcessor daggerCompiler testAnnotationProcessor daggerCompiler androidTestAnnotationProcessor daggerCompiler compile "com.google.dagger:dagger:$DAGGER_VERSION" } kapt { generateStubs = true }
基本上这个https://github.com/ribot/android-boilerplate转化为Kotlin。
Kotlin使用kapt
而不是Android插件的annotationProcessor
。
您需要在build.gradle
文件中包含并使用以下内容:
kapt { generateStubs = true } dependencies { // ... kapt daggerCompiler }
更详细的说明也可以在这里找到: 匕首和Kotlin