[英]@Autowired but got lateinit property testBean has not been initialized error
I have following class (partial code):我有以下 class (部分代码):
@Component
class TestClass: InitializingBean, DisposableBean {
@Autowired
private lateinit var testBean: SomeObject
override fun afterPropertiesSet(){
log.info("testBean 1: $testBdean")
}
fun testFunction(testName: String): Boolean {
log.info("testBean 2: $testBdean")
}
@Throws(Exception::class)
override fun destroy() {
}
}
I saw testBean 1 was run successfully but testBean 2 gave error: lateinit property testBean has not been initialized.我看到 testBean 1 运行成功,但是 testBean 2 报错:lateinit 属性 testBean 没有被初始化。 So the testBean bean was initialized in afterPropertiesSet() and not available in other functions?
那么 testBean bean 是在 afterPropertiesSet() 中初始化的,在其他函数中不可用? I know if we put testBean in the constructor TestClass(testBean) it will be initialized and available to all functions.
我知道如果我们将 testBean 放在构造函数 TestClass(testBean) 中,它将被初始化并可供所有函数使用。 But is there another way because TestClass will be called from other packages and not every package can pass the testBean to the constructor.
但是还有其他方法吗,因为 TestClass 将从其他包中调用,并不是每个 package 都可以将 testBean 传递给构造函数。
You could create an object
that holds your TestClass
and use that holder to refer to your create component您可以创建一个包含您的
TestClass
的object
并使用该持有者来引用您的创建组件
something like:就像是:
@SpringBootApplication
class DemoApplication
fun main(args: Array<String>) {
runApplication<DemoApplication>(*args)
}
@Component
class SomeObject(val name:String = "some object")
@Component
class TestClass(val someObject: SomeObject) {
init {
TestClassHolder.testClass = this
}
fun test() = someObject.name
}
object TestClassHolder {
lateinit var testClass: TestClass
}
class NotBeanClass {
fun call() = TestClassHolder.testClass.test()
}
@RestController
class TestController {
@GetMapping
fun test() = NotBeanClass().call()
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.