Kotlin Ktor项目集成MapStruct编译失败问题求助
初始编译错误场景
在Kotlin Ktor多模块项目中引入MapStruct,配置依赖如下:
implementation("org.mapstruct:mapstruct:$mapStructVersion") kapt("org.mapstruct:mapstruct-processor:$mapStructVersion")
编译时触发如下错误:
Task :modules:backend-api:category:category-impl:kaptKotlin FAILED
C:\Users\zwo7a\Desktop\freshood\FreshNearMe\modules\backend-api\category\category-impl\build\tmp\kapt3\stubs\main\application\CategoryApiImpl.java:4: error: cannot find symbol
public final class CategoryApiImpl extends CategoryApi {
^
symbol: class CategoryApiExecution failed for task ':modules:backend-api:category:category-impl:kaptKotlin'.
A failure occurred while executing org.jetbrains.kotlin.gradle.internal.KaptWithoutKotlincTask$KaptExecutionWorkAction
java.lang.reflect.InvocationTargetException (no error message)
生成的Java stub代码中,CategoryApiImpl继承的CategoryApi无法被识别;对应的Kotlin实现代码为:
internal class CategoryApiImpl(private val categoryRepository: CategoryRepository) : CategoryApi { override suspend fun getCategoryById(id: String): CategoryApiDto { return categoryRepository.getCategoryById(id) as CategoryApiDto //临时类型转换,待映射完成后修改 } } interface CategoryApi { suspend fun getCategoryById(id: String): CategoryApiDto } data class CategoryApiDto( val id: String, val name: String, val parentId: String? = null, val path: String )
项目采用多模块结构,category-impl依赖category-api模块。
补充测试发现的问题
注释所有Category相关代码后编译恢复正常,但在category-api模块中添加任意Kotlin接口时,编译再次失败,Java接口可正常使用,同时出现大量非法反射访问警告,最终错误为:
Execution failed for task ':modules:backend-api:category:category-api:kaptGenerateStubsTestKotlin'.
java.io.IOException: The system cannot find the path specified
解决方案
1. 修正模块依赖与接口可见性
- 确保category-impl模块正确依赖category-api模块,在
category-impl/build.gradle.kts中添加:dependencies { implementation(project(":modules:backend-api:category:category-api")) // 其他依赖... } - 将Kotlin接口
CategoryApi改为public可见性(默认internal仅模块内可见,kapt生成的Java stub无法访问):public interface CategoryApi { suspend fun getCategoryById(id: String): CategoryApiDto }
2. 调整Kapt配置与版本兼容性
- 确保Kotlin插件版本、MapStruct版本与JDK版本兼容:推荐使用Kotlin 1.9.20+、MapStruct 1.5.5.Final+
- 若category-api模块无注解处理器需求,移除该模块的kapt依赖,避免触发不必要的kapt stub生成任务
- 在项目根目录
gradle.properties中添加JVM参数解决反射警告:org.gradle.jvmargs=--illegal-access=permit
3. 优化Kapt任务配置
在模块的build.gradle.kts中添加kapt的生成目录配置,避免路径找不到的问题:
kapt { arguments { arg("mapstruct.defaultComponentModel", "spring") // 若使用Spring,可根据项目调整 } generateStubs = true }
4. 清理缓存并重新编译
执行以下Gradle命令清理缓存后重新编译:
./gradlew clean build --no-build-cache
内容的提问来源于stack exchange,提问作者Antek -

