gpt4 book ai didi

guice - 使用 Kotlin 和 Guice 注入(inject)实例失败

转载 作者:行者123 更新时间:2023-12-01 03:25:40 25 4
gpt4 key购买 nike

我有以下代码:

class Test {

private val context = Context().apply {
property = "foo"
}

private val injector = Guice.createInjector(Module { it.bind(Context::class.java).toInstance(context) })

@Test
fun `service received correct context`() {
assertThat(injector.getInstance(Service::class.java).context.property, equalTo("foo"))
}

}

class Service @Inject constructor(val context: Context)

class Context {
@Inject lateinit var property: String
}

运行它时,测试失败,提示(正确地)空字符串不是“foo”。但是为什么 Guice 不使用我精心创建并以 Module 形式提供给注入(inject)器的实例? ? (这是第一个问题。)

但是,如果我更改 Context看起来像这样:
class Context {
@get:Inject lateinit var property: String
}

测试突然成功了。我真的不明白为什么 Guice 在看 Context如果我绑定(bind)了 Context类到我创建的实例。谁能告诉我这里发生了什么?

最佳答案

Guice 自动注入(inject)传递给 toInstance() 的实例在绑定(bind)语句中,所以 @Inject Context 上的注释是相关的。

在您的示例中,Guice 没有创建 Context 的新实例。 ,但使用空字符串注入(inject)实例的字段。

当您注释属性时,Kotlin 会将注释放在字段上。当您注释 getter 时,Guice 会忽略它。

关于guice - 使用 Kotlin 和 Guice 注入(inject)实例失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41845083/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com