TL;DR
在做的一个项目遇到这个问题,需要把server.host存在application.properties里面,但是在取value 的时候遇到了问题,总是提示 ”lateinit property *** has not been initialized“,找遍了简书和so 都没有太好的答案,多方参考以后终于才解决这个小问题。
这个问题的存在是因为在spring 跑到@service class的时候,我们还没有取到配置文件里面的value, 所以导致了spring 认为这个value variable没有initialize。
解决方案就是把你要取的value放到class的constructor里面去,下面提供一个简单的example。
-application.properties
server.host=localhost:9092
-Service.kt
@Service
class Service(@Value("\${server.host}") val host: String) {
private val producer = createProducer(host)
}
Reference:
Kotlin Doc - Constructor
Another code example