@Qualifier原因:字段注入时[Dagger / MissingBinding] [英] @Qualifier causes: [Dagger/MissingBinding] when field injecting

查看:373
本文介绍了@Qualifier原因:字段注入时[Dagger / MissingBinding]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了这个问题:


ApplicationComponent.java:8:错误:[Dagger / MissingBinding] @ ... java如果没有@Provides注释的方法,则无法提供.text.SimpleDateFormat。

ApplicationComponent.java:8: error: [Dagger/MissingBinding] @... java.text.SimpleDateFormat cannot be provided without an @Provides-annotated method.

模块

@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

Class

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

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

Even if I add @Target(AnnotationTarget.VALUE_PARAMETER, AnnotationTarget.FUNCTION, AnnotationTarget.PROPERTY) to the Qualifier and change the class constructor to @param:CalendarPickerDateFormat, I get the same error.

缺少什么?

可能的解决方案

添加 @JvmStatic 如:

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

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

Solves constructor injection but not field injection:

@Inject
@CalendarPickerDateFormat lateinit var date : SimpleDateFormat

为什么?

注意:我也尝试过 @Module对象类 方法,但我有相同的结果。

NOTE: I've tried also the @Module object class approach but I have the same outcome.

推荐答案

我在 google / Daggers回购和此 PR 将对此进行修复。实际上,这不是错误,正如 zsmb13 所述:

I've opened an issue in google/Daggers repo and this PR will "fix" this. Actually, this is not a bug and as zsmb13 mentioned:


来自Kotlin官方文档:

From the official Kotlin docs:

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

有多个适用目标,则使用以下列表中的第一个适用目标

there are multiple applicable targets, the first applicable target from the following list is used:

    param;
    property;
    field.

基本上,这是因为当未指定
时,param是默认目标。

So basically, it's because param is the default target when it's not specified.

但是此PR对于将来避免这种情况非常有用。

But this PR will be very helpful to avoid this situations in the future.

编辑 Dagger 2.25.2对其进行了修复

这篇关于@Qualifier原因:字段注入时[Dagger / MissingBinding]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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