1. 问题现象与背景分析
当你在SpringBoot项目中整合MyBatis时,控制台突然抛出"SqlSessionFactoryBean未找到"的错误,这通常意味着Spring容器在初始化过程中无法正确创建或注入这个关键Bean。作为Java开发者最常用的ORM组合之一,SpringBoot+MyBatis的集成本应通过starter自动配置完成大部分工作,但实际开发中仍会遇到各种配置问题。
这个错误的典型堆栈信息通常如下:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sqlSessionFactory' defined in class path resource [...]: Invocation of init method failed; nested exception is java.lang.IllegalStateException: SqlSessionFactoryBean requires DataSource2. 核心原因深度解析
2.1 依赖缺失问题
最常见的原因是项目缺少必要的MyBatis-Spring桥接依赖。虽然spring-boot-starter-mybatis已经包含了基础依赖,但在多模块项目或特殊版本组合时可能出现问题。检查你的pom.xml/gradle.build是否包含:
<dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.2.0</version> <!-- 版本需与SpringBoot匹配 --> </dependency>注意:如果使用MyBatis-Plus则需要替换为mybatis-plus-boot-starter,两者不可共存
2.2 数据源配置问题
SqlSessionFactoryBean的核心依赖是DataSource,检查要点包括:
- 是否配置了spring.datasource.*属性
- 是否在@SpringBootApplication主类上添加了@MapperScan
- 多数据源场景下是否漏配了@Primary注解
2.3 自动配置冲突
当存在多个配置源时可能导致冲突:
- 同时存在XML配置和JavaConfig配置
- 自定义的SqlSessionFactoryBean与自动配置产生冲突
- 多模块项目中重复扫描Mapper接口
3. 解决方案与实操步骤
3.1 基础修复方案
步骤1:验证依赖树
mvn dependency:tree | grep mybatis # 应看到mybatis-spring-boot-starter及其传递依赖步骤2:最小化配置示例
@SpringBootApplication @MapperScan("com.example.mapper") // 关键注解 public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } }application.yml配置示例:
spring: datasource: url: jdbc:mysql://localhost:3306/test username: root password: 123456 driver-class-name: com.mysql.cj.jdbc.Driver mybatis: mapper-locations: classpath:mapper/*.xml configuration: map-underscore-to-camel-case: true3.2 高级排查技巧
技巧1:调试自动配置在application.properties中添加:
debug=true启动时会打印自动配置报告,搜索"MyBatisAutoConfiguration"查看匹配情况。
技巧2:手动定义SqlSessionFactory当自动配置失效时,可手动创建:
@Configuration public class MyBatisManualConfig { @Bean @Primary public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception { SqlSessionFactoryBean factory = new SqlSessionFactoryBean(); factory.setDataSource(dataSource); factory.setMapperLocations(new PathMatchingResourcePatternResolver() .getResources("classpath*:mapper/**/*.xml")); return factory.getObject(); } }4. 典型场景解决方案
4.1 多模块项目配置
在父子工程中常见问题:
- 将@MapperScan放在父项目启动类上
- Mapper接口与XML文件分散在不同模块
正确做法:
// 在每个需要扫描的模块定义自己的配置类 @Configuration @MapperScan( basePackages = "com.module.dao", sqlSessionFactoryRef = "sqlSessionFactory" ) public class ModuleMyBatisConfig { // 单独配置数据源和SqlSessionFactory }4.2 自定义MyBatis配置
需要覆盖默认配置时:
mybatis: config-location: classpath:mybatis-config.xml type-aliases-package: com.example.model executor-type: BATCH警告:config-location和configuration属性不能同时使用
5. 预防措施与最佳实践
版本对齐原则:
- MyBatis-Spring版本需与SpringBoot版本匹配
- 通过starters管理依赖而非直接引入jar
配置检查清单:
- 数据源URL格式正确(时区参数等)
- Mapper接口与XML命名空间一致
- 资源文件目录被正确打包(检查target/classes)
日志监控建议:
logging.level.org.mybatis=DEBUG logging.level.org.springframework.jdbc.datasource=TRACE6. 疑难问题排查指南
当基础方案无效时,按以下步骤深入排查:
- 检查Bean定义:
ConfigurableApplicationContext ctx = SpringApplication.run(Application.class, args); String[] beanNames = ctx.getBeanNamesForType(SqlSessionFactory.class); System.out.println(Arrays.toString(beanNames));- 验证数据源连接:
@Bean public CommandLineRunner testDataSource(DataSource dataSource) { return args -> { try(Connection conn = dataSource.getConnection()) { System.out.println("Connection test: " + conn.isValid(1000)); } }; }- 分析类加载情况: 在启动命令添加:
java -verbose:class -jar your-app.jar | grep SqlSessionFactoryBean7. 扩展知识:MyBatis初始化流程
理解SqlSessionFactoryBean的工作机制有助于问题排查:
初始化阶段:
- 读取mybatis-config.xml(如果指定)
- 解析mapperLocations路径
- 构建Configuration对象
关键时序:
DataSource注入 → 创建SqlSessionFactoryBean → 调用getObject() → 生成SqlSessionFactory → 注册Mapper接口 → 生成代理类常见卡点:
- XML文件语法错误
- 类型处理器注册缺失
- 数据库方言不匹配
8. 企业级方案建议
对于复杂生产环境:
- 多数据源方案:
@Configuration public class DataSourceConfig { @Bean @ConfigurationProperties("spring.datasource.primary") public DataSource primaryDataSource() { return DataSourceBuilder.create().build(); } @Bean public SqlSessionFactory primarySqlSessionFactory( @Qualifier("primaryDataSource") DataSource dataSource) throws Exception { SqlSessionFactoryBean factory = new SqlSessionFactoryBean(); factory.setDataSource(dataSource); // 其他自定义配置 return factory.getObject(); } }- 性能优化配置:
mybatis: configuration: cache-enabled: true lazy-loading-enabled: true default-fetch-size: 100 default-statement-timeout: 30- 监控集成:
- 通过Micrometer暴露MyBatis指标
- 使用P6Spy记录真实SQL
- 集成Arthas进行运行时诊断
9. 版本兼容性参考
以下是经过验证的稳定组合:
| SpringBoot | MyBatis | MyBatis-Spring | JDK |
|---|---|---|---|
| 2.7.x | 3.5.10 | 2.0.7 | 8-17 |
| 2.6.x | 3.5.9 | 2.0.6 | 8-17 |
| 2.5.x | 3.5.7 | 2.0.6 | 8-16 |
特别提醒:SpringBoot 3.x需要MyBatis-Spring 3.x及以上版本
10. 实战经验分享
冷门坑点:
- 使用JUnit 5时,@SpringBootTest需要显式添加properties:
@SpringBootTest(properties = "spring.config.location=classpath:/application-test.yml") - 当使用Spring Cloud时,注意bootstrap.yml的加载顺序
- 使用JUnit 5时,@SpringBootTest需要显式添加properties:
高效调试技巧:
- 在IDEA中开启"Build project automatically"
- 使用MyBatis X-Ray插件可视化SQL映射
- 设置断点在SqlSessionFactoryBean的afterPropertiesSet()方法
架构设计建议:
- 将MyBatis配置与业务代码分离
- 为不同环境准备profile-specific配置
- 对核心Mapper接口添加@Repository注解
遇到特别棘手的问题时,可以尝试以下终极解决方案:
- 清理Maven本地仓库后重新构建
- 删除.idea目录和iml文件后重新导入项目
- 使用Docker隔离环境测试
- 对比官方示例项目spring-boot-mybatis-sample