启用kapt时出现Enum注解值需为枚举常量的异常求助
问题解决:启用kapt后@RequestMapping枚举参数编译报错
问题场景
Kotlin Spring Controller代码中使用@RequestMapping指定method为RequestMethod.POST/GET,一旦添加kapt依赖启用kapt编译,就会触发如下错误:
/upside-core/build/tmp/kapt3/stubs/main/upside/controllers/jobs/raywhite/RayWhiteSyncListingsController.java:43: error: an enum annotation value must be an enum constant @org.springframework.web.bind.annotation.RequestMapping(value = {"/all/{org}"}, method = {org.springframework.web.bind.annotation.RequestMethod.POST, org.springframework.web.bind.annotation.RequestMethod.GET})
明明RequestMethod.POST是合法枚举常量,却被判定为非法值。环境:Spring Boot 2.7.11、Kotlin 1.8.21/1.9.0-RC、Java 17。
解决方案
1. 改用Spring组合注解(推荐)
直接替换@RequestMapping为@PostMapping和@GetMapping的组合,完全避开枚举值的引用问题:
@RestController @RequestMapping("/api/v2/job/raywhite-sync/listings") class RayWhiteSyncListingsController() { @PostMapping("/all/{org}") @GetMapping("/all/{org}") fun syncAllListingsInit(@PathVariable("org") org : String): Ok { return Ok.ok() } }
2. 对齐Kotlin与kapt插件版本
确保kotlin-gradle-plugin和kapt依赖的版本完全一致,比如在build.gradle.kts中:
plugins { kotlin("jvm") version "1.8.21" kotlin("kapt") version "1.8.21" id("org.springframework.boot") version "2.7.11" }
版本不匹配可能导致kapt生成Java stub时出现注解解析错误。
3. 临时调整kapt配置(workaround)
在build.gradle.kts中添加kapt参数,强制stub生成时正确处理枚举引用:
kapt { arguments { arg("kapt.kotlin.generated", "${project.buildDir}/generated/kapt") } useBuildCache = false }
如果还不行,尝试关闭worker api:
kapt { useWorkerApi = false }
原因分析
这个问题本质是kapt在生成Java stub文件时,错误地将Kotlin代码中导入的枚举类全路径展开,导致注解中的枚举值变成了全限定名形式,而Java编译器不接受这种形式的枚举常量引用(要求直接写枚举常量名,而非全路径)。
内容的提问来源于stack exchange,提问作者HJED
相关产品推荐
相关产品推荐

