繁体   English   中英

@Autowired 但得到了 lateinit 属性 testBean has not been initialized 错误

[英]@Autowired but got lateinit property testBean has not been initialized error

我有以下 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() {
        
    }
}

我看到 testBean 1 运行成功,但是 testBean 2 报错:lateinit 属性 testBean 没有被初始化。 那么 testBean bean 是在 afterPropertiesSet() 中初始化的,在其他函数中不可用? 我知道如果我们将 testBean 放在构造函数 TestClass(testBean) 中,它将被初始化并可供所有函数使用。 但是还有其他方法吗,因为 TestClass 将从其他包中调用,并不是每个 package 都可以将 testBean 传递给构造函数。

您可以创建一个包含您的TestClassobject并使用该持有者来引用您的创建组件

就像是:

@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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM