Dagger2 - 如何将@Named 与@BindsInstance 一起使用

Dagger2 - How to use @Named with @BindsInstance

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

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

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

并尝试注入 MyApplication

@Inject
@Named("PreferenceName")
lateinit var prefName : String

但它因字符串缺少绑定而失败。我可以使用模块提供程序解决此问题,但尽量避免提供常量。

更新: 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.

相关: