kotlinspring-annotationsspring-expression-language

Syntax error when using Spring @ConditionalOnExpression in Kotlin


I import in a Kotlin configuration class the

org.springframework.boot.autoconfigure.condition.ConditionalOnExpression

but I get the error message of An annotation argument must be a compile-time constant from IntelliJ when I use the annotation with Spring expression language on a bean definition

@ConditionalOnExpression("${xxx.enabled:true} or ${yyy.enabled:true}")

The xxx.enabled and yyy.enabled are configured in a yml file.

What could be the problem? Thanks.


Solution

  • In Kotlin, the $ operator is used for string interpolation. When your annotation contains @ConditionalOnExpression("${xxx.enabled:true} or ${yyy.enabled:true}") it tries to interpolate whatever is in the curly braces into your string - this makes the string not a compile-time constant. You need to escape the $ to tell the Kotlin compiler not to treat that as an interpolated String. Spring will inject the values into the annotation at run time.

    @ConditionalOnExpression("\${xxx.enabled:true} or \${yyy.enabled:true}")