Spring @Value Annotation in Kotlin Throws an Error Must Be a Compile-Time Constant

Continuing on some short posts from the Spring project I’m working on, I’ve got stuck a bit with injecting a value from properties file with @Value annotation.

The following code didn’t work:

@Component
class Example(
    @Value("${property.from.properties.file}")) private val property: String,
) {
 //...
}

The error I was getting was: An annotation argument must be a compile-time constant

Looking at the code from Spring, it’s clear that I was writing the correct code. However, it is correct for Java. But Kotlin already has it’s ${} syntax in strings for concatenation, so this was showing an obvious error, but I didn’t get it at first.

The simple fix is just to escape with \ and the code will look like this now:

@Component
class Example(
    @Value("\${property.from.properties.file}")) private val property: String,
) {
 //...
}

Everything is the same except "\${property... part.

Hope this helps someone, and for myself, it will serve as a reference.