gpt4 book ai didi

kotlin - Dagger2 - 如何使用 @Named 和 @BindsInstance

转载 作者:行者123 更新时间:2023-12-02 12:47:24 24 4
gpt4 key购买 nike

@Named 如何与 @BindsInstance 一起使用?我有这个组件

interface AppComponent : AndroidInjector<MyApplication>{
@Component.Builder
abstract class Builder : AndroidInjector.Builder<MyApplication>() {

@BindsInstance
abstract fun preferenceName( @Named("PreferenceName") name : String ) : Builder
}
}

并尝试注入(inject) MyApplication
@Inject
@Named("PreferenceName")
lateinit var prefName : String

但它因字符串的 MissingBinding 而失败。我可以使用模块提供程序解决此问题,但要避免提供常量提供程序。

最佳答案

更新: Dagger 2.25.2消除了对解决方法的需要:

  1. Kotlin support

    ii. Qualifier annotations on fields can now be understood without The need for @field:MyQualifier (646e033)

    iii. @Module object classes no longer need @JvmStatic on the provides methods. (0da2180)



这与 @BindsInstance 没有任何关系,而是 @Named字段上的注释。您可以从“MissingBinding for String”中看出,否则会给您一个有关命名字符串的错误。

如 Svetlozar Kostadinov 的文章 Correct usage of Dagger 2 @Named annotation in Kotlin ,您需要向 Kotlin 说明您希望将注释应用于该字段。
@field:[Inject Named("PreferenceName")]
lateinit var prefName : String;

正如 Svetlozar 所说:

The reason is because in Kotlin annotations need to be slightly more complicated in order to work as expected from Java perspective. That’s coming from the fact that one Kotlin element may be a facade of multiple Java elements emitted in the bytecode. For example a Kotlin property is a facade of an underlying Java member variable, a getter and a setter. You annotate the property but what Dagger expects to be annotated is the underlying field.



相关: Dagger 2 constructor injection in kotlin with Named arguments

关于kotlin - Dagger2 - 如何使用 @Named 和 @BindsInstance,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54115182/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com