使用Mybatis-Plus AutoGenerator 代码生成器报错 'AutoGenerator()' has private access in 'com.baomidou.mybatis'
在 Spring Boot 项目中使用 MyBatis-Plus 的代码生成器 AutoGenerator
时,若出现错误 **'AutoGenerator()' has private access in 'com.baomidou.mybatisplus.generator.AutoGenerator'
**,通常是因为 MyBatis-Plus 版本升级导致构造方法变为私有。
以下是解决方案:
问题原因
从 MyBatis-Plus 3.5.0 版本开始,AutoGenerator
的默认构造方法被标记为私有,强制开发者使用新的 建造者模式(Builder Pattern) 来创建实例。旧版本(如 3.4.x)中直接通过 new AutoGenerator()
实例化的方式已失效。
解决方法
根据 MyBatis-Plus 版本选择对应方案:
1. 升级到 3.5.0+ 版本并使用新的 Builder API
步骤:
确认依赖版本:确保
pom.xml
或build.gradle
中使用的是 3.5.0+ 版本:<dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-generator</artifactId> <version>3.5.4</version> <!-- 使用最新版本 --> </dependency>
使用 Builder 模式重构代码:
// 示例:基于 Builder 模式的新 API DataSourceConfig dataSourceConfig = new DataSourceConfig .Builder("jdbc//localhost:3306/test", "root", "password") .build(); GlobalConfig globalConfig = new GlobalConfig.Builder() .outputDir(System.getProperty("user.dir") + "/src/main/java") // 输出目录 .author("YourName") // 作者 .enableSwagger() // 开启 Swagger .disableOpenDir() // 不打开目录 .build(); PackageConfig packageConfig = new PackageConfig.Builder() .parent("com.example.demo") .moduleName("member") // 模块名 .entity("entity") // 实体类包名 .mapper("mapper") // Mapper接口包名 .build(); StrategyConfig strategyConfig = new StrategyConfig.Builder() .addInclude("user") // 指定生成的表名 .addTablePrefix("cm_") // 指定表名的前缀 .entityBuilder() // 实体类策略 .enableLombok() // 开启 Lombok .naming(NamingStrategy.underline_to_camel) // 数据库表映射到实体的命名策略 .columnNaming(NamingStrategy.underline_to_camel) // 数据库表字段映射到实体的命名策略 .build(); AutoGenerator generator = new AutoGenerator.Builder(dataSourceConfig); // 创建 AutoGenerator 对象 autoGenerator.global(globalConfig) // 设置全局配置 .packageInfo(packageConfig) // 设置包配置 .strategy(strategyConfig); // 设置策略配置 .build(); autoGenerator.execute(); // 执行生成
2. 降级到 3.4.x 版本(不推荐)
如果因兼容性问题暂时无法升级代码,可降级到旧版本:
<dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-generator</artifactId> <version>3.4.1</version> <!-- 旧版本 --> </dependency>
注意:旧版本可能存在已知问题或安全漏洞,建议尽快适配新版本。
验证步骤
清理并重新编译项目:确保依赖已正确下载。
检查导入的类路径:确认
AutoGenerator
来自com.baomidou.mybatisplus.generator
。运行生成器:执行代码生成逻辑,观察是否成功生成实体类、Mapper 等文件。
其他可能问题
依赖冲突:检查是否有其他库引入了旧版本 MyBatis-Plus,使用 Maven/Gradle 的依赖树分析工具排查。
IDE 缓存:清理 IDE 缓存并重启(如 IntelliJ 的
File > Invalidate Caches
)。
通过上述调整,代码生成器应能正常运行。若问题依旧,建议参考 MyBatis-Plus 官方文档 或查看版本更新日志。
版权声明
本文仅代表作者观点,未经许可,不得转载。