我正在使用Dagger 2.24。当我编译以下内容
fun main() {
val myClass = MyClass()
}
class MyClass {
@Inject
lateinit var stringMe: String
init {
DaggerMyComponent.create().subComponent().inject(this)
println(stringMe)
}
}
@Component
interface MyComponent {
fun subComponent(): MySubcomponent
fun inject(a: MyClass)
}
@Subcomponent(modules = [MeSubModule::class])
interface MySubcomponent {
fun inject(a: MyClass)
}
@Module
class MeSubModule {
@Provides
fun stringMe(): String = "Hi here"
}
错误指出
error: [Dagger/MissingBinding] java.lang.String cannot be provided without an @Inject constructor or an @Provides-annotated method.
public abstract interface MyComponent {
^
A binding with matching key exists in component: com.elyeproj.modular1bottombase.MySubcomponent
java.lang.String is injected at
com.elyeproj.modular1bottombase.MyClass.stringMe
com.elyeproj.modular1bottombase.MyClass is injected at
com.elyeproj.modular1bottombase.MyComponent.inject(com.elyeproj.modular1bottombase.MyClass)
然后,我注释掉下面的简单行,全部编译正常。
fun main() {
val myClass = MyClass()
}
class MyClass {
@Inject
lateinit var stringMe: String
init {
DaggerMyComponent.create().subComponent().inject(this)
println(stringMe)
}
}
@Component
interface MyComponent {
fun subComponent(): MySubcomponent
// fun inject(a: MyClass) // Comment this out.
}
@Subcomponent(modules = [MeSubModule::class])
interface MySubcomponent {
fun inject(a: MyClass)
}
@Module
class MeSubModule {
@Provides
fun stringMe(): String = "Hi here"
}
怀疑这是Dagger 2的错误,但是如果我错过任何事情,就在这里写?
显然,只要在inject(a: MyClass)
中具有以下MyComponent
,在编译时,它将尝试验证MyComponent
是否能够满足@Inject
所需的所有MyClass
依赖项。
@Component
interface MyComponent {
fun subComponent(): MySubcomponent
fun inject(a: MyClass) // Comment this out.
}
在上述情况下,MyClass
需要String
,但是MyComponent
本身不具备提供String
的能力。所以失败了。当前的注释编译会进行检查,并且实际上是否存在wired up都没有关系。