简体   繁体   中英

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

I have following class (partial code):

@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. So the testBean bean was initialized in afterPropertiesSet() and not available in other functions? I know if we put testBean in the constructor TestClass(testBean) it will be initialized and available to all functions. But is there another way because TestClass will be called from other packages and not every package can pass the testBean to the constructor.

You could create an object that holds your TestClass and use that holder to refer to your create component

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()

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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