Dagger2-如何将@Named与@BindsInstance一起使用 [英] Dagger2 - How to use @Named with @BindsInstance

查看:159
本文介绍了Dagger2-如何将@Named与@BindsInstance一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How is @Named used with @BindsInstance? I have the this component

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

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

并尝试注入MyApplication

and trying to inject in MyApplication

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

但是由于缺少MissingBinding for String而失败。我可以使用模块提供程序解决此问题,但尝试避免使用常量提供程序。

But it fails with MissingBinding for String. I could resolve this with a module provider but trying to avoid provider for constants.

推荐答案

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

Update: Dagger 2.25.2 has eliminated the need for workaround:



  1. 科特琳支持

  1. Kotlin support

ii。现在无需
就可以理解字段上的限定符注释了。@field:MyQualifier(646e033)

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

iii的需要。 @Module对象类不再需要
提供的方法上的@JvmStatic。 (0da2180)

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







此与 @BindsInstance 没有任何关系,而是与字段上的 @Named 批注无关。您可以从 MissingBinding for String中分辨出来,否则会给您有关命名字符串的错误。


This doesn't have anything to do with @BindsInstance, but rather the @Named annotations on fields. You can tell from the "MissingBinding for String", which would otherwise give you an error about a Named string.

如Svetlozar Kostadinov的文章在Kotlin中正确使用Dagger 2 @Named注释 ,则需要向Kotlin澄清您希望将注释应用于字段。

As in Svetlozar Kostadinov's article Correct usage of Dagger 2 @Named annotation in Kotlin, you'll need to clarify to Kotlin that you'd like the annotations to apply to the field.

@field:[Inject Named("PreferenceName")]
lateinit var prefName : String;

正如Svetlozar所说:

As Svetlozar puts it:


原因是因为在Kotlin中,注释需要稍微复杂一些才能从Java角度按预期进行工作。这是因为一个Kotlin元素可能是字节码中发出的多个Java元素的外观。例如,Kotlin属性是基础Java成员变量,getter和setter的外观。您对属性进行了注释,但是Dagger希望对其进行注释的是基础字段。

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.

相关:在Kotlin中使用命名参数将Dagger 2构造函数注入

这篇关于Dagger2-如何将@Named与@BindsInstance一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆