Kotlin + Dagger2:没有@Inject构造函数或@ Provides-或@ Produces-注释方法无法提供 [英] Kotlin + Dagger2: cannot be provided without an @Inject constructor or from an @Provides- or @Produces-annotated method

查看:347
本文介绍了Kotlin + Dagger2:没有@Inject构造函数或@ Provides-或@ Produces-注释方法无法提供的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到以下错误:

错误:(8,1)错误:没有@Inject构造函数或@ Provides-或@ Produces-注释方法无法提供java.lang.String.

Error:(8, 1) error: java.lang.String cannot be provided without an @Inject constructor or from an @Provides- or @Produces-annotated method.

我一直在尝试制作一个提供两个合格字符串的模块.这是匕首的简化设置.

I'm stuck trying to make a module that provides two qualified Strings. Here is the simplified setup of dagger.

@Singleton
@Component(modules = [GreetingsModule::class])
interface AppComponent {
    fun inject(activity: MainActivity)
}

@Qualifier annotation class Spanish
@Qualifier annotation class French
@Qualifier annotation class English

@Module
@Singleton
class GreetingsModule {

    @Provides
    @Spanish
    fun providesHola(): String = "Hola mundo! - From Dagger"

    @Provides
    @English
    fun providesHello(): String = "Hello world! - From Dagger"

}

在MainActivity中的注入方式为:

The injection is done in MainActivity as:

class MainActivity : AppCompatActivity() {

    @Inject @Spanish
    lateinit var holaMundoText: String

    @Inject @English
    lateinit var helloWorldText: String

}

我也尝试直接在组件中声明吸气剂,但失败并出现相同的错误.将模块方法声明为静态时相同.

I also tried declaring the getters directly in the component, but it failed with the same error. Same when declaring the module methods as static.

正如应该的那样,该代码仅对一个@Provide起作用,然后将字符串插入两个字段中.我认为问题出在预选赛上.

Just as should be, the code works fine with only one @Provide, then the string is injected in both fields. I assume the problem is with the qualifier.

我们非常感谢您的帮助.

Any help is highly appreciated.

使用:

  • Android Studio 3.0.1
  • 科特林1.2.10
  • 匕首2.14.1

推荐答案

在使用JSR-330 + Kotlin进行合格且命名的注入时有些麻烦(Dagger2是此实现).通过最近回顾Github上Dagger2项目的积压工作,我知道Google团队正在寻求在即将发布的版本中(无时限)提供更主动的帮助/更有用的错误消息.

There is a bit of a gotcha with qualified and named injection with JSR-330 + Kotlin (Dagger2 is an implementation of this). From recently reviewing the backlog on the Dagger2 project on Github I know the Google team are looking to provide more proactive assistance/more helpful error messages within a forthcoming release (no timescales).

您所缺少的是@field:<Qualifier> 注释使用-按照链接文档中的说明输入目标.所以尝试;

What you are missing is the @field:<Qualifier> annotation use-type targets as described in the linked documentation. So try;

@Inject @field:Spanish lateinit var holaMundoText: String

这篇关于Kotlin + Dagger2:没有@Inject构造函数或@ Provides-或@ Produces-注释方法无法提供的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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