【问题标题】:Syntax error when using Spring @ConditionalOnExpression in Kotlin在 Kotlin 中使用 Spring @ConditionalOnExpression 时出现语法错误
【发布时间】:2022-09-28 02:54:40
【问题描述】:

我在 Kotlin 配置类中导入

org.springframework.boot.autoconfigure.condition.ConditionalOnExpression

但是当我在 bean 定义上使用带有 Spring 表达式语言的注释时,我从 IntelliJ 收到了 An annotation argument must be a compile-time constant 的错误消息

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

xxx.enabled 和 yyy.enabled 在 yml 文件中配置。

可能是什么问题呢?谢谢。

  • 您可能需要将注释转义为 @ConditionalOnExpression(\"\\${xxx.enabled:true} or \\${yyy.enabled:true}\")
  • @MarkAbersold 请将此作为答案,我会选择它。

标签: kotlin spring-annotations spring-expression-language


【解决方案1】:

我相信你应该使用 ConditionalOnProperty 而不是 ConditionalOnExpression 在引用例如值时应用程序.yml。

@ConditionalOnProperty(prefix="xxx", name="enabled", havingValue="true")

检查真/假时,havingValue 是多余的,可能会被删除(请参阅doc 了解更多信息)。

@Conditional 检查指定的属性是否具有特定的 价值。默认情况下,属性必须存在于环境中 并且不等于假。 haveValue() 和 matchIfMissing() 属性允许进一步定制。

haveValue() 属性可用于指定 属性应该有。

Annotation Type ConditionalOnProperty in Spring doc

【讨论】:

    【解决方案2】:

    在 Kotlin 中,$ 运算符用于字符串插值。当您的注释包含 @ConditionalOnExpression("${xxx.enabled:true} or ${yyy.enabled:true}") 时,它会尝试将大括号中的任何内容插入到您的字符串中 - 这使得字符串不是编译时常量。您需要转义 $ 以告诉 Kotlin 编译器不要将其视为内插字符串。 Spring 将在运行时将值注入注解中。

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

    【讨论】:

      猜你喜欢
      • 2013-10-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-10
      • 2020-09-21
      相关资源
      最近更新 更多