在 Kotlin 中,变量必须在声明时初始化,并且不能为 null
,除非它在类型名称后附加了 ?
。因此,要由 Spring 注入(inject)的 bean 引用必须声明为:
@AutoWired
var someService: SomeService? = null
令人讨厌的地方显然是,从这里开始,在所有使用 someService
的地方,都必须指定某种空安全逻辑,无论是 ?:
还是直接的 -进行空检查。
我们当然可以:
@AutoWired
var someService = new SomeService()
但这并不总是可能的,而且一次性实例只是令人困惑。
我的问题是,是否有办法告诉 Kotlin 该变量将被初始化并且实际上不是 null
?
最佳答案
您有两个选择。
1)使用构造函数注入(inject)
我认为构造函数注入(inject)是最好的方法,因为它明确声明必须设置依赖关系才能构造对象。
2) 将您的字段声明为 Lateinit
阅读文档中有关该主题的更多信息: https://kotlinlang.org/docs/reference/properties.html
Late-Initialized Properties
Normally, properties declared as having a non-null type must be initialized in the constructor. However, fairly often this is not convenient. For example, properties can be initialized through dependency injection, or in the setup method of a unit test. In this case, you cannot supply a non-null initializer in the constructor, but you still want to avoid null checks when referencing the property inside the body of a class.
public class MyTest {
lateinit var subject: TestSubject
@SetUp fun setup() {
subject = TestSubject()
}
@Test fun test() {
subject.method() // dereference directly
}
}
关于java - Kotlin 中的 Spring 注入(inject)引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46731607/