[英]How to use @value annotation in kotlin data class
我有一个 application.properties 文件,例如:
person-one-name=John
这是我的数据 class,我在数据类之外使用了@Value 注解。
@Value("\${person-one-name}")
lateinit var personOne: String
data class Person(val name: String, val age: Int) {
constructor(age: Int) : this(personOne, age)
}
我想在我的数据 class 中使用 var personOne。
它给出了一个错误 lateinit property personOne has not been initialized
根据我在问题下的评论:
data class Person(val name: String, val age: Int)
@Service
class PersonFactory(
@Value("\${person-one-name}")
private val personOne: String,
) {
fun createPerson(name: String? = null, age: Int) =
if (name != null) Person(name, age)
else Person(personOne, age)
}
另一个问题是, PersonFactory
服务需要位于同一级别的 package 中,或者位于启动 App 的 class 中。
更多信息: https://springhow.com/a-guide-to-value-in-spring-boot/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.