Kotlin 扩展 spring 引导注释

Kotlin extending spring boot annotations

使用 Kotlin,我可以在 class 级别注释中保存默认值,例如

@Profile("dev", "staging", "production")
annotation class RemoteProfile

我很好奇是否有一种方法可以实现与参数注释类似的东西 - 例如,我希望能够做类似的事情:

fun someHandler(@AccountParam account: Account) {
   ...
}

spring 下方的位置会将其解释为

fun someHandler(@RequestAttribute("ACCOUNT") account: Account) {
   ...
}

您正在寻找的概念是元注释。您的第一个示例起作用的原因与 Kotlin 无关,而是 Spring 的一个特性,其中 Spring 主动检查注释层次结构。来自 the Javadoc for Profile:

The @Profile annotation may be used in any of the following ways:

  • as a meta-annotation, for the purpose of composing custom stereotype annotations

MVC 注释 RequestAttributeRequestParam 不支持元注释。你可以定义你自己的 HandlerMethodArgumentResolvers 来支持这个(它并不 可怕 复杂,你可以继承 RequestAttributeMethodArgumentResolver),但你不能只是元注释一般。

(Groovy的AnnotationCollector 确实支持这个,但它是通过编译时“展开”实现的,我不相信Kotlin 具有等效功能。)