当我尝试使用 SPeL 表达式注入(inject)一个值时,它在 Java 中有效,但在 Kotlin 中无效。编译器说
Error:(13, 25) Kotlin: An annotation parameter must be a compile-time constant
代码:
@SpringBootApplication
open class DeDup(@Value("#{new java.io.File('${roots}')}") val roots: Set<File>,
@Value("algo") val hashAlgo: String,
@Value("types")val fileTypes: List<String>) {
}
fun main(args: Array<String>) {
SpringApplication.run(DeDup::class.java, *args)
}
嗯...新闻快讯 Kotlin 编译器:它是一个常量!编译器清楚地知道它是一个 SPeL 表达式并且不喜欢它。
我的问题:
为什么 Kotlin 不喜欢 SPeL?这是一个构造注入(inject)(或者是它)并且不违反不变性。
这是编译器错误吗?消息无疑是错误的。
最佳答案
${roots}
在 Kotlin 中的字符串中是 string template ,因此 String 不是常数。
如果您希望字符串包含这些实际字符而不被解释为模板,则必须转义 $
:
@Value("#{new java.io.File('\${roots}')}")
关于spring - Kotlin 编译器提示在属性定义中使用 SPeL 表达式。为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44506762/