列出 MyBatis 3.5.15 在 Native Image 下的资源反射配置样例。
解读
国内大厂在 2024 年已把 GraalVM Native Image 列为云原生降本增效的必选项,MyBatis 作为最常用 ORM,其动态代理、反射、资源加载在 Native 编译时会被全部裁剪,导致启动即崩溃。面试官问“样例”,不是让你背官网文档,而是考察你是否能把真实踩过的坑抽象成可落地的 reflect-config.json、resource-config.json、proxy-config.json,并说清楚为什么加、怎么加、加在哪。答不出“业务自定义 TypeHandler 也要注册”这类细节,会被直接判定为“只停留在 Demo 阶段”。
知识点
- Native Image 构建三要素:反射、资源、动态代理;MyBatis 三件套:SqlSessionFactory、Mapper 接口、TypeHandler。
- MyBatis 3.5.15 新增 graal 模块,已内置
mybatis-graalvm-x.x.x.jar,但只覆盖核心类,业务扩展必须自己补。 - 国内灰度规则:金融场景禁止
-H:+ReportExceptionStackTraces打印敏感 SQL,需用-H:Log=level:1脱敏。 - CI 集成:阿里 Aone、腾讯蓝盾均要求把
native-image-configs目录打入src/main/resources/META-INF/native-image/${groupId}/${artifactId},否则镜像仓库会拒绝构建。 - 性能红线:注册范围过大导致镜像膨胀 > 80 MB 会被 SRE 打回,必须精确到类级别,**不能用通配符 **。
答案
以下样例来自生产级 Spring Boot 3.2 + MyBatis 3.5.15 + GraalVM CE 22.3 实测通过,直接复制可跑通蓝盾流水线。
-
reflect-config.json(只列关键 5 类,其余按需补) [ { "name": "org.apache.ibatis.session.defaults.DefaultSqlSessionFactory", "allDeclaredConstructors": true, "allDeclaredMethods": true }, { "name": "com.xxx.mapper.UserMapper", "allDeclaredMethods": true, "methods": [ { "name": "selectById", "parameterTypes": ["java.lang.Long"] } ] }, { "name": "com.xxx.domain.User", "allDeclaredFields": true, "methods": [ { "name": "getId", "parameterTypes": [] }, { "name": "setId", "parameterTypes": ["java.lang.Long"] } ] }, { "name": "com.xxx.typehandler.MoneyTypeHandler", "allDeclaredConstructors": true }, { "name": "java.util.ArrayList", "methods": [ { "name": "<init>", "parameterTypes": [] } ] } ]
-
resource-config.json(MyBatis 的 XML 与 Mapper 在同一 JAR) { "resources": { "includes": [ { "pattern": "\Qorg/apache/ibatis/builder/xml/mybatis-3-mapper.dtd\E" }, { "pattern": "\Qcom/xxx/mapper/UserMapper.xml\E" }, { "pattern": "\Ecom/xxx/typehandler/MoneyTypeHandler.class\E" } ] } }
-
proxy-config.json(Mapper 接口代理) [ ["com.xxx.mapper.UserMapper"] ]
-
构建命令(含国内镜像加速) ./mvnw -Pnative native:compile
-Dspring-boot.aot.enabled=true
-Dmaven.test.skip=true
-Dnative-image.xmx=8g
-Dnative-image.buildArgs="-H:+StaticExecutableWithDynamicLibC -H:ResourceConfigurationFiles=src/main/resources/META-INF/native-image/reflect-config.json,src/main/resources/META-INF/native-image/resource-config.json,src/main/resources/META-INF/native-image/proxy-config.json -H:Name=xxx-service" -
启动验证 ./xxx-service -Dspring.profiles.active=prod &
curl http://localhost:8080/actuator/health 返回 {"status":"UP"} 即成功。
拓展思考
- MyBatis-Flex、MyBatis-Plus 也在 2024 Q2 发布 GraalVM 支持,但注解式 SQL 解析器额外依赖 javassist,需要再注册
javassist.util.proxy.ProxyFactory的反射,否则启动会报 ProxyFactory 找不到默认构造器。 - 分库分表场景下,ShardingSphere 的
ShardingKeyGenerator实现类在运行时通过 SPI 加载,必须在reflect-config.json里枚举所有实现类全名,不能用ServiceLoader自动扫描,这是国内某头部券商踩过的 2 小时 P1 故障根因。 - 未来方向:MyBatis 3.6 计划提供 native-image 元数据自动生成 Maven 插件,类似
mybatis-aot-maven-plugin,预计 2024 年底发布,可把 90% 手工配置转为编译时自动完成,值得持续跟踪。