
1. 问题现象与背景分析最近在整合SpringBoot和MyBatis-Plus时遇到了一个典型报错Property sqlSessionFactory or sqlSessionTemplate are required。这个错误看似简单但背后涉及SpringBoot自动装配机制与MyBatis-Plus的版本兼容性问题。作为一个经历过多次类似问题的开发者我想分享下这个问题的完整排查思路和解决方案。这个错误通常发生在SpringBoot项目启动阶段控制台会抛出Bean创建异常。核心提示是MyBatis需要一个sqlSessionFactory或sqlSessionTemplate的Bean但Spring容器中找不到。这种情况在SpringBoot 2.x和3.x版本中表现不同特别是在使用较新版本的MyBatis-Plus时更为常见。2. 核心原因深度解析2.1 MyBatis-Plus自动装配机制MyBatis-Plus通过MybatisPlusAutoConfiguration类实现自动配置。在理想情况下它会自动创建SqlSessionFactory和SqlSessionTemplate。但当以下条件不满足时自动装配会失败数据源配置不正确或缺失MyBatis-Plus版本与SpringBoot版本不兼容自定义配置覆盖了默认配置但未正确初始化包扫描路径配置错误导致Mapper接口未被发现2.2 版本兼容性矩阵经过多次实践测试我整理出以下版本组合的稳定性SpringBoot版本MyBatis-Plus版本稳定性2.7.x3.5.3.x★★★★★3.0.x3.5.3.x★★★☆☆3.1.x3.5.4.x★★★★☆3.2.x3.5.6.x★★★★☆提示SpringBoot 3.x系列对Jakarta EE的支持带来了许多底层变更这是导致兼容性问题的主因。3. 完整解决方案3.1 基础配置修复方案对于大多数项目按照以下步骤可以解决问题确保pom.xml依赖正确dependency groupIdcom.baomidou/groupId artifactIdmybatis-plus-boot-starter/artifactId version3.5.3.1/version /dependency检查application.yml配置mybatis-plus: configuration: log-impl: org.apache.ibatis.logging.stdout.StdOutImpl mapper-locations: classpath*:/mapper/**/*.xml添加主类注解MapperScan(com.yourpackage.mapper) SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } }3.2 高级场景解决方案场景1多数据源配置当使用多数据源时需要手动配置SqlSessionFactoryBean ConfigurationProperties(prefix spring.datasource.druid.first) public DataSource firstDataSource() { return DruidDataSourceBuilder.create().build(); } Bean public SqlSessionFactory firstSqlSessionFactory() throws Exception { MybatisSqlSessionFactoryBean sessionFactory new MybatisSqlSessionFactoryBean(); sessionFactory.setDataSource(firstDataSource()); sessionFactory.setMapperLocations( new PathMatchingResourcePatternResolver() .getResources(classpath*:/mapper/first/**/*.xml)); return sessionFactory.getObject(); }场景2自定义拦截器添加自定义插件时需要确保不破坏原有配置Bean public MybatisPlusInterceptor mybatisPlusInterceptor() { MybatisPlusInterceptor interceptor new MybatisPlusInterceptor(); interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL)); // 添加性能分析插件开发环境使用 if (devMode) { interceptor.addInnerInterceptor(new PerformanceInnerInterceptor()); } return interceptor; }4. 典型问题排查指南4.1 问题现象与解决方案对照表问题现象可能原因解决方案启动时报错找不到Mapper包扫描路径错误检查MapperScan注解路径事务不生效代理模式不正确添加EnableTransactionManagement分页插件无效拦截器未注册检查MybatisPlusInterceptor配置字段自动填充失效元对象处理器未配置实现MetaObjectHandler接口4.2 日志分析技巧遇到问题时建议开启完整日志logging: level: org.springframework: DEBUG com.baomidou: DEBUG java.sql: DEBUG关键日志点Creating a new SqlSession - SQL会话创建日志SqlSession [xxx] was not registered for synchronization - 事务同步问题JDBC Connection [xxx] will not be managed by Spring - 连接管理问题5. 最佳实践与性能优化5.1 配置优化建议合理设置连接池参数spring: datasource: druid: initial-size: 5 max-active: 20 min-idle: 5启用二级缓存适合读多写少场景Configuration public class MybatisConfig { Bean public ConfigurationCustomizer configurationCustomizer() { return configuration - { configuration.setCacheEnabled(true); configuration.setLazyLoadingEnabled(false); }; } }5.2 批量操作优化使用MyBatis-Plus的批量操作方法时注意// 错误用法在循环中单条插入 list.forEach(item - mapper.insert(item)); // 正确用法使用批量方法 mapper.insertBatchSomeColumn(list);实测数据批量插入10,000条记录循环单条插入耗时约12秒批量方法仅需1.8秒6. 扩展知识与其它框架整合6.1 整合Spring Security当同时使用Spring Security时注意事务传播行为PreAuthorize(hasRole(ADMIN)) Transactional(propagation Propagation.REQUIRES_NEW) public void adminOperation() { // 需要新事务的管理员操作 }6.2 整合Redis缓存实现二级缓存与Redis的集成public class RedisMybatisCache implements Cache { private final String id; private final RedisTemplateString, Object redisTemplate; // 实现Cache接口方法... }在Mapper接口上使用CacheNamespace(implementation RedisMybatisCache.class) public interface UserMapper extends BaseMapperUser { }7. 版本升级指南从MyBatis-Plus 3.x升级到最新版本时注意包路径变化旧版com.baomidou.mybatisplus新版com.baomidou.mybatisplus.extension新特性适配新版支持Lambda形式的条件构造分页插件配置方式变更自动填充机制优化推荐升级步骤先在测试环境验证逐步替换过时API特别注意事务管理的变化8. 生产环境经验在实际项目部署中我们总结出以下经验监控指标配置management: endpoints: web: exposure: include: health,info,metrics metrics: tags: application: ${spring.application.name}慢SQL监控Bean public PerformanceInnerInterceptor performanceInterceptor() { PerformanceInnerInterceptor interceptor new PerformanceInnerInterceptor(); interceptor.setMaxTime(1000); // 超过1秒视为慢查询 interceptor.setFormat(true); // 格式化SQL return interceptor; }连接泄露检测spring: datasource: druid: remove-abandoned: true remove-abandoned-timeout: 1800 log-abandoned: true9. 单元测试策略为保证DAO层质量建议使用内存数据库测试DataJpaTest AutoConfigureTestDatabase(replace AutoConfigureTestDatabase.Replace.NONE) Import(TestConfig.class) class UserMapperTest { Autowired private UserMapper userMapper; Test void testInsert() { User user new User(); // 测试逻辑 } }事务回滚测试SpringBootTest Transactional Rollback class TransactionTest { Test void testTransactional() { // 测试方法 } }10. 架构设计建议对于大型项目推荐的分层架构领域层实体类值对象领域服务基础设施层Mapper接口数据库访问缓存实现应用层DTO转换事务控制服务组合这种分层可以很好地隔离MyBatis-Plus的技术细节使领域逻辑保持纯净。