为什么 guice requestInjection 对 Kotlin 对象不起作用

Why doesn't guice requestInjection work on Kotlin object

我是 Guice 新手。我正在尝试使用 requestInjection 以这种方式注入 kotlin 单例 object 的依赖项。

方法 1:

class SampleTest {

    @Test
    fun test() {
        Guice.createInjector(object: KotlinModule() {
            override fun configure() {
                requestInjection(A)
            }
        })
        assertEquals("Hello world", A.saySomething())
    }
}

object A {
    @Inject
    private lateinit var b: B

    fun saySomething(): String {
        return b.sayHello()
    }
}

class B {
    fun sayHello(): String {
        return "Hello world"
    }
}

但是我收到这个错误:

kotlin.UninitializedPropertyAccessException: lateinit property b has not been initialized

如果我将 A 更改为具有无参数构造函数的 class,它会起作用。

方法 2:

class SampleTest {

    @Test
    fun test() {
        val a = A()
        Guice.createInjector(object: KotlinModule() {
            override fun configure() {
                requestInjection(a)
            }
        })
        assertEquals("Hello world", a.saySomething())
    }
}

class A {
    @Inject
    private lateinit var b: B

    fun saySomething(): String {
        return b.sayHello()
    }
}

class B {
    fun sayHello(): String {
        return "Hello world"
    }
}

相反,如果我将 requestInjection 更改为 requestStaticInjection,它也有效。

方法 3:

class SampleTest {

    @Test
    fun test() {
        Guice.createInjector(object: KotlinModule() {
            override fun configure() {
                requestStaticInjection<A>()
            }
        })
        assertEquals("Hello world", A.saySomething())
    }
}

object A {
    @Inject
    private lateinit var b: B

    fun saySomething(): String {
        return b.sayHello()
    }
}

class B {
    fun sayHello(): String {
        return "Hello world"
    }
}

为什么 方法 1 不起作用?为什么 方法 2方法 3 有效?

Kotlin 的对象被视为语言静态单例,即它们的 initialization/instantiations 发生在依赖注入框架的范围之外。

因此,当使用 KotlinModule 注入对象时,您必须像 APPROACH 3 中那样使用 requestStaticInjection,或者将该对象更改为class,因此 Guice KotlinModule 将其视为 non-static,如 APPROACH 2

中所示

希望能澄清一些事情。