MyBatis-Spring整合核心:SqlSessionFactoryBean深度解析

news/2025/11/20 2:36:53/文章来源:https://www.cnblogs.com/irobotzz/p/19244576

MyBatis-Spring整合核心:SqlSessionFactoryBean深度解析

MyBatis-Spring整合核心:SqlSessionFactoryBean深度解析

概述

在MyBatis与Spring框架的整合中,SqlSessionFactoryBean扮演着至关重要的角色。它是连接两个框架的桥梁,负责在Spring容器中创建和管理MyBatis的核心组件。本文将深入分析这个关键类的作用、重要性以及其配置方式。

核心地位与作用

1. Spring整合的入口点

SqlSessionFactoryBean是MyBatis-Spring整合的核心工厂Bean,它实现了Spring的FactoryBean接口,负责创建和管理MyBatis的SqlSessionFactory实例。

public class SqlSessionFactoryBean implements FactoryBean<SqlSessionFactory>, InitializingBean, ApplicationListener<ContextRefreshedEvent> {// 核心实现
}

2. 三大接口职责

  • FactoryBean: 作为工厂Bean,创建并返回SqlSessionFactory实例
  • InitializingBean: 在属性设置完成后执行初始化逻辑
  • ApplicationListener: 监听Spring容器刷新事件,执行完整性检查

核心初始化流程

初始化时序图

sequenceDiagramparticipant SC as Spring Containerparticipant SFB as SqlSessionFactoryBeanparticipant Config as Configurationparticipant Builder as SqlSessionFactoryBuilderSC->>SFB: 设置所有属性(Setter注入)SC->>SFB: afterPropertiesSet()SFB->>SFB: buildSqlSessionFactory()SFB->>Config: 创建Configuration对象SFB->>Config: 注册类型别名/处理器/插件SFB->>Config: 解析Mapper XML文件SFB->>Builder: build(targetConfiguration)Builder->>SFB: 返回SqlSessionFactorySFB->>SC: 返回SqlSessionFactory实例SC->>SFB: onApplicationEvent() [failFast检查]

关键初始化方法

@Override
public void afterPropertiesSet() throws Exception {// 1. 验证必要属性notNull(dataSource, "Property 'dataSource' is required");notNull(sqlSessionFactoryBuilder, "Property 'sqlSessionFactoryBuilder' is required");// 2. 构建SqlSessionFactorythis.sqlSessionFactory = buildSqlSessionFactory();
}

依赖注入机制

传统Setter注入模式

与基于注解的现代Spring应用不同,SqlSessionFactoryBean采用传统的Setter注入方式,这体现了其作为框架基础组件的设计理念。

必须注入的依赖

1. 数据源(DataSource)- 必须

private DataSource dataSource;public void setDataSource(DataSource dataSource) {if (dataSource instanceof TransactionAwareDataSourceProxy) {this.dataSource = ((TransactionAwareDataSourceProxy) dataSource).getTargetDataSource();} else {this.dataSource = dataSource;}
}

2. Mapper文件位置(强烈推荐)

private Resource[] mapperLocations;public void setMapperLocations(Resource... mapperLocations) {this.mapperLocations = mapperLocations;
}

重要可选依赖

1. 类型别名配置

// 扫描包路径
public void setTypeAliasesPackage(String typeAliasesPackage) {this.typeAliasesPackage = typeAliasesPackage;
}// 直接指定类
public void setTypeAliases(Class<?>... typeAliases) {this.typeAliases = typeAliases;
}

2. 插件系统(拦截器)

private Interceptor[] plugins;public void setPlugins(Interceptor... plugins) {this.plugins = plugins;
}

3. 类型处理器

public void setTypeHandlers(TypeHandler<?>... typeHandlers) {this.typeHandlers = typeHandlers;
}public void setTypeHandlersPackage(String typeHandlersPackage) {this.typeHandlersPackage = typeHandlersPackage;
}

配置示例

1. 传统XML配置方式

<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"><property name="dataSource" ref="dataSource"/><property name="mapperLocations" value="classpath*:mapper/**/*.xml"/><property name="typeAliasesPackage" value="com.example.entity"/><property name="typeHandlersPackage" value="com.example.handler"/><property name="plugins"><array><bean class="com.github.pagehelper.PageInterceptor"><property name="properties"><value>helperDialect=mysqlreasonable=true</value></property></bean></array></property>
</bean>

2. 现代Java配置方式

@Configuration
public class MyBatisConfig {@Bean@ConfigurationProperties(prefix = "mybatis")public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception {SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();sessionFactory.setDataSource(dataSource);// 自定义配置sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/**/*.xml"));return sessionFactory.getObject();}
}

3. Spring Boot自动配置

# application.yml
mybatis:mapper-locations: classpath:mapper/**/*.xmltype-aliases-package: com.example.entitytype-handlers-package: com.example.handlerconfiguration:map-underscore-to-camel-case: truecache-enabled: true

核心功能解析

1. Configuration对象管理

SqlSessionFactoryBean负责创建和配置MyBatis的核心Configuration对象:

protected SqlSessionFactory buildSqlSessionFactory() throws Exception {final Configuration targetConfiguration;if (this.configuration != null) {targetConfiguration = this.configuration;} else if (this.configLocation != null) {// 从XML配置文件创建xmlConfigBuilder = new XMLConfigBuilder(this.configLocation.getInputStream(), null, this.configurationProperties);targetConfiguration = xmlConfigBuilder.getConfiguration();xmlConfigBuilder.parse();} else {// 创建默认配置targetConfiguration = new Configuration();}// 应用各种配置...return this.sqlSessionFactoryBuilder.build(targetConfiguration);
}

2. Mapper XML解析

在初始化过程中,最重要的步骤之一是解析Mapper XML文件:

if (this.mapperLocations != null) {for (Resource mapperLocation : this.mapperLocations) {XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(mapperLocation.getInputStream(),targetConfiguration, mapperLocation.toString(), targetConfiguration.getSqlFragments());xmlMapperBuilder.parse(); // 解析XML中的SQL语句}
}

3. 插件系统集成

SqlSessionFactoryBean负责注册所有配置的插件(拦截器):

if (!isEmpty(this.plugins)) {Stream.of(this.plugins).forEach(plugin -> {targetConfiguration.addInterceptor(plugin);LOGGER.debug(() -> "Registered plugin: '" + plugin + "'");});
}

设计模式与架构思想

1. 工厂模式(Factory Pattern)

作为FactoryBean,它封装了复杂对象的创建过程,客户端只需获取最终产品。

2. 模板方法模式(Template Method Pattern)

buildSqlSessionFactory()方法定义了创建过程的骨架,具体步骤可以通过配置定制。

3. 依赖注入(Dependency Injection)

通过Setter方法接受依赖,而不是在内部创建,符合依赖倒置原则。

4. 建造者模式(Builder Pattern)

SqlSessionFactoryBuilder协作,完成复杂对象的逐步构建。

重要性体现

1. 性能优化关键

通过在应用启动时一次性完成所有XML解析和配置初始化,避免了运行时的重复解析,极大提升了性能。

2. 配置集中管理

作为统一的配置入口,集中管理所有MyBatis相关配置,提高了可维护性。

3. 扩展性基础

通过插件机制和丰富的配置选项,为框架扩展提供了坚实基础。

4. 事务集成核心

与Spring事务管理紧密集成,确保数据访问层的事务一致性。

最佳实践

1. 必要配置检查

// 始终配置数据源和Mapper位置
sessionFactory.setDataSource(dataSource);
sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:mapper/**/*.xml"));

2. 合理使用类型别名

// 为实体类包配置类型别名,简化Mapper XML配置
sessionFactory.setTypeAliasesPackage("com.example.entity");

3. 插件配置优化

// 按需配置插件,避免不必要的性能开销
Interceptor[] plugins = new Interceptor[]{pageInterceptor(), sqlLogInterceptor()};
sessionFactory.setPlugins(plugins);

4. 启用failFast检查

// 在开发环境中启用failFast,及时发现问题
sessionFactory.setFailFast(true);

故障排查

常见问题及解决方案

  1. DataSource未设置

    Error: Property 'dataSource' is required
    

    解决方案:确保正确注入DataSource Bean

  2. Mapper XML文件未找到

    Warning: Property 'mapperLocations' was specified but matching resources are not found
    

    解决方案:检查Mapper文件路径和模式匹配

  3. 类型别名/处理器扫描失败
    解决方案:确认包路径正确,类符合扫描条件

总结

SqlSessionFactoryBean是MyBatis-Spring整合的灵魂组件,它不仅是技术实现的桥梁,更是设计思想的体现。通过深入理解其工作原理和配置方式,我们能够:

  • 更合理地配置和优化MyBatis集成
  • 更好地排查和解决集成问题
  • 更充分地利用框架提供的扩展能力
  • 构建更稳定、高效的数据访问层

作为MyBatis在Spring生态系统中的基石,SqlSessionFactoryBean的稳定性和性能直接影响到整个应用的数据访问能力,值得每一个使用MyBatis的开发者深入理解和掌握。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/970533.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Windows-sfc

Windows-sfc导航 (返回顶部)1. sfc1.1 Syntax 1.2 Parameters 1.3 Examples 1.4 扫描修复 1.5 CBS.log 1.6 更多相关链接2. sfc与DISM2.1 主要区别 2.2 参考链接3. chkdsk3.1 Parameters 3.2 HDD-SSD 3.3 查看 chkdsk…

SSH 连接报错 bad ownership or modes for directory 解决

某天某用户突然报告说 SSH 不能登录了,经查看 /var/log/auth.log 发现报错如下: 2025-11-20T01:57:53.957884+08:00 h101 sshd[3191378]: Authentication refused: bad ownership or modes for directory /home/ubun…

高精度进制转换

#include <bits/stdc++.h> using namespace std;int val(char c) { // 字符转值if (c >= 0 && c <= 9) return c - 0;if (c >= A && c <= Z) return c - A + 10;return c - a + 36;…

20232325 2025-2026-1 《网络与系统攻防技术》实验六实验报告

Metasploitable2靶机渗透测试实验报告 1. 实验内容 1.1 前期渗透Metasploitable2靶机,发现靶机并进行端口、漏洞扫描 1.2 Metasploit攻击渗透方法实践 (1)Vsftpd源码包后门漏洞(21端口) (2)SambaMS-RPC Shell命…

AI元人文:赋能技术人文深度融合的法治新范式

AI元人文:赋能技术与人文深度融合的法治新范式 摘要:人工智能的迅猛发展正以前所未有的深度和广度重塑人类社会,同时对建立于工业文明基石之上的传统法治体系构成了系统性挑战。法律的滞后性、规则的抽象性与监管的…

3100+星标开源商城系统!SparkShop:从技术架构到全场景营销的电商解决方案

2025年11月,一款名为SparkShop的开源商城系统在Gitee上悄然突破3100星标,成为国内电商开发者社区的热议焦点。这款基于ThinkPHP 8 + Element UI的免费商用系统,以"插件化架构"和"多端适配"为核…

[K8s/资源调度] Volcano : 基于Kubernetes的【批量】容器【资源调度】平台

1 概述Volcano是 CNCF 下首个也是唯一的基于Kubernetes的容器批量计算平台,主要用于高性能计算场景。 Volcano 是一个开源的 Kubernetes 批处理系统,专为高性能计算任务设计。它提供了一种高效的方式来管理和调度资源…

Yanhua Mini ACDP-2 Volvo 2015-2021: Add Key All Key Lost for Semi/Full-Keyless

The Challenge: Key Issues with Modern Volvo Keyless Systems Modern Volvo keyless systems—whether semi-keyless (traditional remote with push-to-start) or full-keyless (passive entry, start-stop without…

[K8s/资源调度] Vocano : 开源的 Kubernetes 批处理系统

1 概述Volcano是 CNCF 下首个也是唯一的基于Kubernetes的容器批量计算平台,主要用于高性能计算场景。 Volcano 是一个开源的 Kubernetes 批处理系统,专为高性能计算任务设计。它提供了一种高效的方式来管理和调度资源…

2025 Super MB Pro M6+ PRO: BENZ BMW 2-in-1 Diagnostic Tool with Panasonic FZ-G1 Tablet Ready to Use

Streamline Your BENZ & BMW Diagnostics with the 2025 Super MB Pro M6+ PRO: All-in-One, Ready to Work The Pain Points European & American Mechanics and Car Owners Face In today’s fast-paced aut…

广东工业新手赛 我不吃水果

点击查看代码 #include <iostream> using namespace std;const int N = 1005; int n, pre[N][N], ans;int main() {cin >> n;for (int i = 1; i <= n; i++) {for (int j = 1; j <= n; j++) {int x;c…

用PyTorch从零搭建一个Transformer模型 - Sanny.Liu

用PyTorch从零搭建一个Transformer模型Transformer讲解转载:https://blog.csdn.net/2401_85373396/article/details/153516337 Transformer总体上可分为左边的encoder部分、右边的decoder部分。目前主流大模型如deep…

题解:CF2172N New Kingdom

题目大意 给定三个整数 \(n,k,b\)。构造一张有 \(m(0\le m\le 5n)\) 条边的连通简单无向图,满足有 \(k\) 个点的度数为奇数,有 \(b\) 条边是割边 。 解法 这道题思考起来并不困难,但是存在一定数量的 corner case,…

win11 WSL Ubuntu ssh远程连接工具的选择问题

远程终端工具: Xshell, MobaXterm,WindTerm, win cmd ,win powerShell MobaXterm 的缺点查看 https://www.cnblogs.com/CJRiver/p/19244473

11.19 p1115最大字段和

点击查看代码 #include<bits/stdc++.h>using namespace std;int n;int main() {ios::sync_with_stdio(false);cin.tie(nullptr);cout.tie(nullptr);cin>>n;int a,b;int ans=-1e4-1;for(int i=0;i<n;++i…

UEFI-PEI 阶段的深层介绍 - 阿源

一、PEI Core 与 PEIMs PEI Core:是PEI阶段的核心引擎,负责寻找,加载和执行各种PEIM。PEI Core首先首先运行一个小的固定的SEC阶段的代码,这段代码通常使用CPU缓存作为临时内存来运行。一旦找到并初始化了真正的系…

01组-选题与需求分析报告

博客链接:https://www.cnblogs.com/Cindy051010/p/19244480 一、团队集结 1.1 介绍每位组员擅长的编程技术、拟担任的软工角色及拟完成的任务分工等,内容形式不限(3分)成员 擅长的编程技术 软工角色 任务分工龙玉凤…

软工第二次团队作业

成群结队第二次团队作业 原型设计+概要设计作业总览项目 内容作业所属课程 软件工程作业要求 作业要求作业目标 完成项目原型设计与概要设计,形成交互原型、UML模型、数据库结构,并制定开发计划与分工安排。团队名称…

2025市政管道/家装管材优质厂家最新TOP5推荐:云南昆明荣德福领衔,优质PVC管道/管材品牌,聚焦排水家庭/市政管等场景

随着国内基础设施建设与城镇化进程的快速推进,市政管道、家装管材及PVC管道市场需求持续攀升。本榜单基于技术研发实力、区域市场覆盖、产品质量控制、服务网络密度四大维度,结合2025年《中国塑料管道行业发展报告》…

251120

251120惩罚源源不断,欲望肆意横生,没有尽头和终点,忘掉初心和起点,气喘吁吁,作茧自缚。