1 回答
TA贡献1831条经验 获得超10个赞
在您的 java 库的 gradle 文件中:
plugins {
id 'java-library'
id 'kotlin'
id 'kotlin-kapt'
}
java {
sourceCompatibility = JavaVersion.VERSION_1_7
targetCompatibility = JavaVersion.VERSION_1_7
}
dependencies {
implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
//Dependency injection
implementation 'com.google.dagger:dagger:2.27'
kapt 'com.google.dagger:dagger-compiler:2.24'
}
然后创建一个类及其依赖项:
class First
@Inject
constructor(
private val second: Second,
private val third: Third
) {
fun firstFunction() {
print(second.secondMessage())
print(third.name)
}
}
class Second(
private val name: String
) {
fun secondMessage(): String {
return name
}
}
class Third(
val name: String
)
然后创建你的匕首模块:
@Module
class ModuleUtil {
@Provides
fun providesSecond(): Second {
return Second("second")
}
@Provides
fun providesThird(): Third {
return Third("third")
}
}
然后创建你的匕首组件:
@Singleton
@Component(modules = [
ModuleUtil::class
])
interface MainComponent {
fun maker(): First
}
处理生成组件的对象:
object DaggerWrapper {
lateinit var mainComponent: MainComponent
fun initComponent() {
mainComponent = DaggerMainComponent
.builder()
.build()
}
}
最后在你的应用程序 android 模块中(例如,在 Activity 中):
DaggerWrapper.initComponent()
val mainComponent = DaggerWrapper.mainComponent
val first = mainComponent.maker()
first.firstFunction()
添加回答
举报