Kotlin配置Dagger2

在Kotlin中设置Dagger有一些不同,但大多数都非常简单,其中也有不少坑。

1.按照正常步骤创建kotlin项目,(要打开全部设置需要在下图中点config,打开界面选中 全部使用kotlin)

Kotlin配置Dagger2_第1张图片
config.png

2.在 build.gradle中添加相关配置

apply plugin: 'kotlin-android'
apply plugin: 'kotlin-kapt'
apply plugin: 'kotlin-android-extensions'
  compile 'com.android.support.constraint:constraint-layout:1.0.2'
  kapt 'com.google.dagger:dagger-compiler:2.5'

3.按照Dagger的传统三步

3.1创建module

@Module
class AppModule(val app: App) {
    @Provides @Singleton fun provideApp() = app
}

3.2实现Component

@Singleton
@Component(modules = arrayOf(AppModule::class))
interface ApiComonent {
    fun inject(app: App)
}

3.3 创建app

class App : Application() {
    init {
        instance = this
    }
    @Inject lateinit var apiComponent: ApiComonent
    override fun onCreate() {
        super.onCreate()
        DaggerApiComonent.builder().appModule(AppModule(this)).build().
                inject(this)
    }


    companion object {
        lateinit var instance: App
    }
}

如果遇到Circular dependency between the following tasks:这个错误,需要进行降级处理,修改项目根目录里面的build.gradle,

buildscript {
    //此处降级 Circular dependency between the following tasks:
    ext.kotlin_version = '1.1.2-2'

    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.3.1'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
    }
}

allprojects {
    repositories {
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

你可能感兴趣的:(Kotlin配置Dagger2)