java - 问题 当我使用 @Named 注释时,如果没有 @Provides 注释的方法,则无法提供 Dagger

标签 java android kotlin dagger-2

当我将 @Named 注释放入 AppModule 中时,我遇到了问题,这是我的代码,仅当我将 @Named 注释添加到“AppModule”和“IdentityRepository”时,才会出现问题,但是当我将其从两者中删除一切都很好

Note that I have to use @Named because I want to create a second function with the same DataType in the same Module

@Module
object AppModule {
...

    @Provides
    @JvmStatic
    @Singleton
    @Named("NOT_AUTH_IDENTITY_SERVICE")
    fun provideIdentityService(retrofit: Retrofit): IdentityService =
        retrofit.create(IdentityService::class.java)
}

当我使用它时,IdentityRepository

class IdentityRepository @Inject constructor() {

    @Inject
    @Named("NOT_AUTH_IDENTITY_SERVICE")
    lateinit var identityService: IdentityService
...
}

我遇到这个错误

error: [Dagger/MissingBinding] solutions IdentityService cannot be provided without an @Provides-annotated method. public abstract interface AppComponent extends dagger.android.AndroidInjector { ...

最佳答案

已关注 the documentation :

When you're annotating a property or a primary constructor parameter, there are multiple Java elements which are generated from the corresponding Kotlin element, and therefore multiple possible locations for the annotation in the generated Java bytecode. To specify how exactly the annotation should be generated.

在 Kotlin 中使用 Named 提供程序时,您必须使用 @field 注释显式注释 field:

class IdentityRepository @Inject constructor() {

    @Inject
    @field:Named("NOT_AUTH_IDENTITY_SERVICE")
    lateinit var identityService: IdentityService
...
}

或者您可以将属性移动到构造函数,因为您也在使用构造函数注入(inject):

class IdentityRepository @Inject constructor(
    @Named("NOT_AUTH_IDENTITY_SERVICE") val identityService: IdentityService
) {
...
}

关于java - 问题 当我使用 @Named 注释时,如果没有 @Provides 注释的方法,则无法提供 Dagger,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58817498/

相关文章:

java - 使用jsoup获取url的异常调度输入事件

java - 删除文本时如何隐藏 Eclipse 中的建议框?

java - 概念 : Build Java Program and load it into Oracle DB - Wrapper function calls java function with return

android - VirtualBox Linux 无法挂载安卓设备

spring-boot - 构建一个可以使用 `publishToMavenLocal` 发布到 maven 本地存储库的可执行 jar - spring boot 项目

java - 如何从 CURL 访问静态端点

java - 通过 Android 中的蓝牙打印机多次打印

android - 是否有任何单一字体支持所有 android 设备中的所有印度语言?

kotlin - 函数中带有和不带有 'suspend' lambda 的“重载分辨率歧义”

kotlin - Kotlin中的内联构造函数是什么?