【问题标题】:@Qualifier causes: [Dagger/MissingBinding] when field injecting@Qualifier 原因:字段注入时 [Dagger/MissingBinding]
【发布时间】:2019-09-03 23:31:26
【问题描述】:

我遇到了这个问题:

ApplicationComponent.java:8: error: [Dagger/MissingBinding] @... java.text.SimpleDateFormat 不能在没有@Provides-annotated 方法的情况下提供。

模块

@Module
abstract class ApplicationModule {

    @Binds
    @AppContext
    abstract fun application(app: App): Context

    @Module
    companion object {
        ...

        @Provides
        @Singleton
        @CalendarPickerDateFormat
        fun provideCalendarPickerDateFormat(): SimpleDateFormat {
            return SimpleDateFormat("dd/MMM/yyyy", Locale.getDefault())
        }
    }
}

限定符

@Qualifier
@Retention(AnnotationRetention.RUNTIME)
annotation class CalendarPickerDateFormat

@ActivityScope
class MyClass
@Inject constructor(
   ...,
    @CalendarPickerDateFormat private val calendarDateFormat: SimpleDateFormat
) {...}

即使我将 @Target(AnnotationTarget.VALUE_PARAMETER, AnnotationTarget.FUNCTION, AnnotationTarget.PROPERTY) 添加到 Qualifier 并将类构造函数更改为 @param:CalendarPickerDateFormat,我也会收到相同的错误。

缺少什么?

可能的解决方案

添加@JvmStatic 喜欢:

@Provides
@Singleton
@JvmStatic
@CalendarPickerDateFormat
fun provideCalendarPickerDateFormat(): SimpleDateFormat {
      return SimpleDateFormat("dd/MMM/yyyy", Locale.getDefault())
}

解决构造函数注入但不解决字段注入:

@Inject
@CalendarPickerDateFormat lateinit var date : SimpleDateFormat

为什么?

注意:我也尝试过@Module object class approach,但结果相同。

【问题讨论】:

    标签: android kotlin dependency-injection dagger-2


    【解决方案1】:

    我在google/Daggers repo 中打开了一个问题,这个PR 将“修复”这个问题。实际上,这不是错误,正如 zsmb13 所述:

    来自 Kotlin 官方文档:

    If you don't specify a use-site target, the target is chosen according to the @Target annotation of the annotation being used. If
    

    有多个适用目标,第一个适用目标 使用以下列表:

        param;
        property;
        field.
    

    所以基本上,这是因为 param 不是默认目标 指定。

    但是这个 PR 对以后避免这种情况很有帮助。

    编辑Dagger 2.25.2 fixes it.

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-12-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多