1. 问题背景与现象分析
最近在整合SpringBoot和MyBatisPlus时,不少开发者遇到了这个典型的启动报错:"Property 'sqlSessionFactory' or 'sqlSessionTemplate' are required"。这个错误通常发生在项目启动阶段,控制台会直接抛出IllegalStateException导致应用无法正常启动。作为一个经历过这个坑的老手,我来详细解析下这个问题的成因和解决方案。
这个报错的本质是MyBatis的自动配置未能正确完成。在SpringBoot的自动配置体系中,MyBatisAutoConfiguration类需要依赖sqlSessionFactory或sqlSessionTemplate这两个关键bean来完成数据访问层的初始化。当系统检测不到这两个bean时,就会抛出这个致命错误。
2. 核心原因深度解析
2.1 配置缺失的常见场景
根据我的项目经验,这个问题通常由以下几种配置问题导致:
- 依赖缺失:项目pom.xml中没有正确引入mybatis-spring-boot-starter
- 配置冲突:同时引入了JPA等其它ORM框架导致自动配置冲突
- 多数据源:在多数据源场景下未正确配置主数据源
- 版本不兼容:MyBatisPlus与SpringBoot版本存在兼容性问题
2.2 自动配置原理剖析
SpringBoot对MyBatis的自动配置主要通过MyBatisAutoConfiguration类实现。这个类会检查以下条件:
- 存在SqlSessionFactory类
- 存在SqlSessionFactoryBean类
- 没有手动定义的SqlSessionFactoryBean
- 没有手动定义的SqlSessionTemplate
当这些条件满足时,SpringBoot会自动创建sqlSessionFactory和sqlSessionTemplate。如果自动配置失败,就需要我们手动提供这些bean。
3. 完整解决方案
3.1 基础配置修复方案
首先确保你的pom.xml包含必要依赖:
<dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.5.3.1</version> </dependency>然后在application.yml中添加基本配置:
mybatis-plus: configuration: log-impl: org.apache.ibatis.logging.stdout.StdOutImpl mapper-locations: classpath*:mapper/**/*.xml3.2 多数据源特殊处理
如果是多数据源项目,需要手动配置主数据源:
@Bean @Primary public DataSource dataSource() { // 你的数据源配置 } @Bean @Primary public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception { MybatisSqlSessionFactoryBean factory = new MybatisSqlSessionFactoryBean(); factory.setDataSource(dataSource); factory.setMapperLocations(new PathMatchingResourcePatternResolver() .getResources("classpath*:mapper/**/*.xml")); return factory.getObject(); }3.3 版本兼容性处理
对于版本冲突问题,推荐使用以下稳定组合:
- SpringBoot 2.7.x + MyBatisPlus 3.5.3.x
- SpringBoot 3.0.x + MyBatisPlus 3.5.4.x
可以在pom.xml中通过 锁定版本:
<dependencyManagement> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-dependencies</artifactId> <version>2.7.12</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement>4. 高级排查技巧
4.1 调试自动配置过程
可以通过在application.properties中添加以下配置来查看自动配置详情:
debug=true启动时会打印CONDITIONS EVALUATION REPORT,其中会显示MyBatis自动配置为何没有生效。
4.2 常见误配置示例
- 错误的主类位置:SpringBoot主类应该放在根包下,确保能扫描到Mapper接口
- 缺少@MapperScan:如果没有使用@Mapper注解,需要在配置类添加@MapperScan
- XML映射文件位置错误:确保mapper-locations配置的路径与实际匹配
4.3 单元测试配置
在测试类中需要额外配置:
@SpringBootTest @AutoConfigureMybatis public class MybatisTest { // 测试代码 }5. 生产环境最佳实践
5.1 性能优化配置
建议在生产环境添加以下配置:
mybatis-plus: configuration: cache-enabled: true lazy-loading-enabled: true aggressive-lazy-loading: false default-executor-type: REUSE5.2 监控集成
集成Micrometer监控SQL执行情况:
@Bean public MybatisPlusInterceptor mybatisPlusInterceptor() { MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor(); // 添加性能分析插件 interceptor.addInnerInterceptor(new PerformanceInnerInterceptor()); return interceptor; }5.3 安全防护
防止全表删除操作:
mybatis-plus: global-config: db-config: logic-delete-field: deleted logic-not-delete-value: 0 logic-delete-value: 1 block-attack: enabled: true delete-never: true6. 扩展思考与进阶方案
6.1 动态数据源处理
对于需要动态切换数据源的场景,建议使用AbstractRoutingDataSource:
public class DynamicDataSource extends AbstractRoutingDataSource { @Override protected Object determineCurrentLookupKey() { return DataSourceContextHolder.getDataSourceType(); } }6.2 MyBatisPlus插件开发
可以自定义插件实现特殊功能,如分页优化:
@Intercepts(@Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class})) public class CustomPaginationInterceptor implements Interceptor { // 实现逻辑 }6.3 与其它框架整合
与Spring Security整合时的特殊处理:
@Configuration @EnableGlobalMethodSecurity(prePostEnabled = true) public class MybatisSecurityConfig extends GlobalMethodSecurityConfiguration { @Override protected MethodSecurityExpressionHandler createExpressionHandler() { // 自定义表达式处理器 } }在实际项目中遇到这个问题时,建议按照以下步骤排查:
- 检查依赖树是否完整
- 确认配置项是否正确加载
- 查看自动配置报告
- 检查Bean创建顺序
- 验证Mapper扫描范围
最后分享一个实用技巧:在IDEA中可以通过"Diagrams -> Show Dependencies"查看项目的依赖关系图,快速发现冲突或缺失的依赖。