配置
build.gradle
apply plugin: 'com.android.library'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-kapt'
...
dependencies {
...
//dagger2
compile rootProject.ext.dependencies["dagger"]
kapt rootProject.ext.apt["dagger-compiler"]
//dagger2 android 一个dagger2 关于Android的增强库 可选项
compile rootProject.ext.dependencies["dagger-android"]
//可选项
compile rootProject.ext.dependencies["dagger-android-support"]
//可选项
kapt rootProject.ext.apt["dagger-android-processor"]
}
AppComponent
@Singleton
@Component(modules = arrayOf(AppModule::class))
interface AppComponent {
fun inject(app: BaseApplication)
}
AppModule
@Module
class AppModule(val app: Application) {
@Provides
@Singleton
fun provideApplication() = app
}
Application
class BaseApplication : Application() {
override fun onCreate() {
super.onCreate()
initApplication()
DaggerCoreComponent
.builder()
.coreModule(CoreModule(this))
.build();
}
}
以上配置完成,就可以愉快的在Kotlin中使用Dagger2了。
坑
- Circular dependency between the following tasks
在使用Kotlin 1.1.2-4 plugin 时,使用kapt,会出现循环依赖的错误,这个错误仅需要将 Kotlin 1.1.2-4降级到Kotlin 1.1.2-2版本即可。
根目录下的build.gradle
buildscript {
//此处降级
ext.kotlin_version = '1.1.2-2'
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:2.3.2'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
apply plugin: 'kotlin'
allprojects {
repositories {
jcenter()
}
}
repositories {
mavenCentral()
}
感谢StackOverFlow