【问题标题】:Kotlin multiple classes in spring @Import春季Kotlin多个类@Import
【发布时间】:2020-01-21 13:21:34
【问题描述】:

我正在使用 kotlin。我有两个春季班,com.example.SpringConfigAcom.example.SpringConfigB。我正在尝试将它们导入com.example.SpringConfigParent,但以下都不起作用:

尝试1,错误:This annotation is not repeatable

@Import(com.example.SpringConfigA)
@Import(com.example.SpringConfigB)
class SpringConfigParent {}

尝试2,错误:Type mismatch: inferred type is () -> ??? but KClass<*> was expected

@Import({com.example.SpringConfigA, com.example.SpringConfigB})
class SpringConfigParent {}

尝试3,错误:Only 'const val' can be used in constant expressions

@Import(arrayOf(com.example.SpringConfigA, com.example.SpringConfigB))
class SpringConfigParent {}    

Kotlin 中的正确语法是什么?

编辑:正如@jaquelinep 建议的那样,我忘了添加::class,尝试一下:

尝试1,错误:This annotation is not repeatable

@Import(com.example.SpringConfigA::class)
@Import(com.example.SpringConfigB::class)
class SpringConfigParent {}

尝试2,错误:Type mismatch: inferred type is () -> KClass<SpringConfigA> but KClass<*> was expected

@Import({com.example.SpringConfigA::class, com.example.SpringConfigB::class})
class SpringConfigParent {}

尝试3,错误:Type inference failed. Expected type mismatch: inferred type is Array<KClass<out Any>> but KClass<*> was expected

@Import(arrayOf(com.example.SpringConfigA::class, com.example.SpringConfigB::class))
class SpringConfigParent {}    

【问题讨论】:

    标签: spring spring-boot kotlin


    【解决方案1】:

    您缺少类名末尾的 .class:

    @Import({com.example.SpringConfigA::class, com.example.SpringConfigB::class})
    class SpringConfigParent {}
    

    感谢 eamon-scullion,我更新了答案

    【讨论】:

    • kotlin应该是SpringConfigA::class.class是java语法
    • 谢谢 - 更新了所有::class,不幸的是同样的错误
    • 不工作:注意问题是关于 kotlin 语法。您不能在 kotlin 中使用花括号作为数组文字 {...,...} 。为此,您应该使用括号 [...,...],请参阅@EamonScullion 答案以获取工作代码 sn-p。
    【解决方案2】:

    一个注解的多个导入的语法如下:

    @Import(value = [Config1::class, Config2::class])
    

    【讨论】:

    • @levantpied 也是,您的第三次尝试非常接近!只需要value = 部分
    猜你喜欢
    • 2020-05-18
    • 2020-07-23
    • 1970-01-01
    • 2019-08-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-28
    • 2021-08-28
    相关资源
    最近更新 更多