I have this dependency:

@Singleton
class SpiceMix @Inject constructor(@field:[Named("oregano")] private val oregano: Spice,
                                   @field:[Named("sage")] private val sage: Spice,
                                   @field:[Named("rosemary")] private val rosemary: Spice) 

以及一个模块来实现其依赖性:

@Module
class SpiceModule {

    @Provides
    @Named("oregano")
    @Singleton
    fun provideOregano(): Spice = Oregano()

    @Provides
    @Named("sage")
    @Singleton
    fun provideSage(): Spice = Sage()

    @Provides
    @Named("rosemary")
    @Singleton
    fun provideRosemary(): Spice = Rosemary()

The SpiceMix is then injected in various locations of my app.

但是,这不会编译,我得到一个错误:

Spice cannot be provided without an @Provides-annotated method

I think the @Named annotations do not quite work in my constructor signature. I am not quite sure how I can make it work.

Note: this compiles fine if I ditch the Named annotations and change the types of the constructor parameters to their concrete forms. However, Spice is an interface, and I need it for mocking purposes in my tests.

我能做什么?

推荐答案

如果要进行构造函数注入,则需要注释构造函数参数,而不是字段-使用@param:注释目标:

@Singleton
class SpiceMix @Inject constructor(@param:Named("oregano") private val oregano: Spice,
                                   @param:Named("sage") private val sage: Spice,
                                   @param:Named("rosemary") private val rosemary: Spice)

编辑:实际上,因为注释目标的分辨率顺序是

  • 帕拉姆;
  • property;
  • field.

according to the docs, having no annotation target should also annotate the parameter of the constructor. So you can just drop the target altogether:

@Singleton
class SpiceMix @Inject constructor(@Named("oregano") private val oregano: Spice,
                                   @Named("sage") private val sage: Spice,
                                   @Named("rosemary") private val rosemary: Spice)

Kotlin相关问答推荐

这些Kotlin函数等效吗?

何时使用figureEach

我可以在kotlin/java.util.scanner中跳过分隔符而不重复吗?

Kotlin:类型不匹配:推断的类型已运行,但应等待

多模块Kotlin项目中的FreeFair

Kotlin stlib中是否有用于将列表<;对<;A,B&>;转换为对<;列表<;A&>,列表<;B&>;的函数

如何使用multiset与JOOQ获取关联的记录列表?

找不到有效的 Docker 环境

在 Compose 中使用 Text() 时如何获取文本的大小?

OnClickListener 未在 ConstraintLayout 上触发

Kotlin 中多个 init 块的用例?

Kotlin 是如何编译的?

requireNotNull vs sure !! 操作符

main函数和常规函数有什么区别?

是否在Kotlin中重写enum toString()?

Kotlin:如何修改成对的值?

如何序列化/反序列化Kotlin密封类?

如何在 IntelliJ IDEA 中禁用粘贴时将 Java 转换为 Kotlin?

如何在 Kotlin 中将串联转换为模板

对有延迟的 Rxjava 可观察对象进行单元测试