Kotlin配置Dagger2

在Kotlin中設(shè)置Dagger有一些不同,但大多數(shù)都非常簡單,其中也有不少坑。

1.按照正常步驟創(chuàng)建kotlin項目,(要打開全部設(shè)置需要在下圖中點config,打開界面選中 全部使用kotlin)

config.png

2.在 build.gradle中添加相關(guān)配置

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的傳統(tǒng)三步

3.1創(chuàng)建module

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

3.2實現(xiàn)Component

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

3.3 創(chuàng)建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:這個錯誤,需要進(jìn)行降級處理,修改項目根目錄里面的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
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容