当我将 @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/