簡體   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