Search code examples
springkotlincompanion-object

How Can I use @Value variable in Companion Object?


class EnumUtils(
        @Value("\${open-date}")
        lateinit var openDateYmd: String
) {
    companion object {
        fun getStatus(orderDate: LocalDateTime): Status {
            val openDateLocalDateTime = parseToLocalDateTime(**openDateYmd**)
            return when {
                orderDate.isBefore(openDateLocalDateTime) -> Status.VALUE_1
                else -> Status.VALUE_1
            }
        }
    }
}

This is My Code. I want to Use openDateYmd variable in companion object.(Specifically, I want to use it inside parseToLocalDateTime function.)

openDateYmd is one of the yaml's variable.

How can I use It ?


Solution

  • In order to use a variable annotated with @Value in the companion object of an Android class, you need to make sure that the variable is declared as a property of the containing class rather than the companion object itself.

    Here's an example of how you can use a variable annotated with @Value in a companion object:

    class MyActivity : AppCompatActivity() {
    
        @Value("\${my_value}")
        lateinit var myValue: String
    
        companion object {
            fun doSomethingStatic() {
                // Access the myValue property through the containing class
                val myValue = MyActivity().myValue
                // ...
            }
        }
    }
    

    In this example, myValue is declared as a property of MyActivity and is annotated with @Value. The lateinit keyword is used to indicate that the property will be initialized at a later time.

    The doSomethingStatic function is declared in the companion object of MyActivity and can access the myValue property through an instance of the containing class. Note that you cannot access the myValue property directly from the companion object, as it is not a static property.