How Can I use @Value variable in Companion Object?

1.3k Views Asked by At
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 ?

2

There are 2 best solutions below

0
drjansari On BEST ANSWER

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.

0
AndrewL On

(I presume you are using Spring, since you mention YAML and @Value.)

How can I use It ?

No you cannot (or least not easily*) - wrong scope.

If you are familiar with Java - the Companion Object is like a static and the @Value annotates a class instance variable.

You could change the class EnumUtils to be a singleton class object EnumUtils which is what you'd normally do for a Utility class where you don't need to have a particular instance, but this won't solve your problem, since Spring wants to create the instance for you (even if it essentially creates a singleton).

* a hack would be to pass the value into the a variable in the companion object but now you are breaking the model and could run into problems if the Companion object has not been "instantiated"

It seem like you need to parameterise your utility. You need to avoid Companion Objects or Object class and stick with a regular class that's managed by Spring and then inject this into the call site.