简体   繁体   中英

How to use @value annotation in kotlin data class

I have an application.properties file like:

person-one-name=John

This is my data class, I have used @Value annotation outside dataclass.

@Value("\${person-one-name}")
lateinit var personOne: String

data class Person(val name: String, val age: Int) {
        constructor(age: Int) : this(personOne, age)
}

I want to use the var personOne in my data class.

It gives an error lateinit property personOne has not been initialized

Following on from my comment under the Question:

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

Another gotcha, is that the PersonFactory service needs to be in a package at the same level or within the class that starts the App.

More info: https://springhow.com/a-guide-to-value-in-spring-boot/

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