在 Gradle 8 中,如何增量编译 APT 生成的文件?
解读
国内一线互联网与金融企业普遍把 MyBatis 的 Mapper 接口 交由 APT(Annotation Processor Tool) 在编译期生成实现类,以彻底摆脱 XML 并享受编译期校验。Gradle 8 默认开启 Build Cache 与 增量编译(Incremental Annotation Processing),但 APT 生成的源码若配置不当,每次都会触发 full recompile,导致 CI 耗时翻倍、本地开发“改一行等 3 分钟”。面试官问“如何增量编译 APT 生成的文件”,实质考察三点:
- 是否理解 Gradle 8 增量注解处理器的隔离/聚合分类;
- 能否让 MyBatis 的 mapper 生成器(如 mybatis-mapper-processor、mybatis-plus-generator)声明为 isolating 并正确输出 generated/sources/annotations;
- 是否会用 Gradle Build Cache + Compile avoidance 把生成的文件缓存到远程节点,实现“一次生成、全团队复用”。
知识点
- Gradle 8 增量注解处理器规范:处理器必须实现
javax.annotation.processing.Processor,并在META-INF/gradle/incremental.annotation.processors中声明为 isolating(每个源文件独立)或 aggregating(多文件聚合)。 - MyBatis 官方 APT(org.mybatis:mybatis-annotations-processor:1.3.1)已支持 isolating 模式,但老项目常引用 mybatis-plus-generator 3.5.x,其处理器未声明增量类型,需手动补丁。
- Gradle 8 编译选项:
–options.incremental = true(默认开启)
–options.annotationProcessorPath = configurations.apt(隔离处理器路径)
–options.compilerArgumentProviders.add { ['-Amybatis.incremental=true'] }(传递自定义参数给 MyBatis 处理器) - Build Cache 路径:
${GRADLE_USER_HOME}/caches/build-cache-1,CI 场景需挂载到 NAS 或 S3 兼容存储(如阿里云 OSS),并在gradle.properties开启org.gradle.caching=true。 - Compile avoidance:只要 ABI(方法签名)不变,下游模块不重新编译;APT 生成的类若仅改变实现体,不会触发 ABI 变动,因此需把 生成的源码目录 声明为
compileOnly避免误依赖。
答案
- 升级 MyBatis 处理器到 官方 isolating 版本(或给 mybatis-plus-generator 打补丁:在
META-INF/gradle/incremental.annotation.processors文件里加一行
com.baomidou.mybatisplus.generator.processor.MapperProcessor isolating)。 - 在
build.gradle.kts(Gradle 8)中显式配置:dependencies { annotationProcessor("org.mybatis:mybatis-annotations-processor:1.3.1") } tasks.withType<JavaCompile> { options.isIncremental = true options.annotationProcessorPath = configurations.annotationProcessor.get() // 让生成的代码落位 build/generated/sources/annotations options.generatedSourceOutputDirectory.set(file("${buildDir}/generated/sources/annotations")) } - 开启 远程 Build Cache(阿里云 OSS 为例):
buildCache { remote<HttpBuildCache> { url = uri("https://your-bucket.oss-cn-hangzhou.aliyuncs.com/cache/") credentials { username = System.getenv("OSS_ACCESS_KEY") password = System.getenv("OSS_SECRET_KEY") } isPush = System.getenv("CI") == "true" } } - 验证增量效果:
若输出 “All annotation processors are incremental.” 且 “Task compileJava UP-TO-DATE”,则增量编译生效,CI 时间可由 3 min 降至 20 s。./gradlew compileJava --info --build-cache | grep "Incremental annotation processing"
拓展思考
- 多模块场景:把 mapper 接口集中放在
api模块,APT 生成后通过 java-library 插件的apiElements暴露,下游service模块仅依赖字节码,不再执行处理器,实现 “一次生成、多模块复用”。 - 与 Spring Boot 3 集成:Spring Boot 3 默认使用 AOT 编译,需把生成的 mapper 实现类提前加入 Spring AOT 索引,否则 native-image 阶段会报 “Type not found”;可通过
spring-aot-maven-plugin的 include 列表把build/generated/sources/annotations加入扫描路径。 - 缓存命中率调优:国内团队常因 Lombok、MapStruct 等处理器未声明为 isolating 导致整包失效,可用 gradle-profiler 扫描热点,把非增量处理器拆分到单独 sourceSet,实现 “混合编译、部分增量”。