当前位置: 首页 > news >正文

Mybatis在SpringBoot中是如何被加载执行

首先依赖于springboot的自动装配@EnableAutoConfiguration注解,这个注解最终帮助我们读取mybatis-spring-boot-autoconfigure-x.x.x.jar中的META-INF\spring.factories配置类:

org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
org.mybatis.spring.boot.autoconfigure.MybatisLanguageDriverAutoConfiguration,\
org.mybatis.spring.boot.autoconfigure.MybatisAutoConfiguration

来看MybatisAutoConfiguration的源码,最主要的就是AutoConfiguredMapperScannerRegistrar。


@Configuration
@ConditionalOnClass({SqlSessionFactory.class, SqlSessionFactoryBean.class})
@ConditionalOnSingleCandidate(DataSource.class)
@EnableConfigurationProperties({MybatisProperties.class})
@AutoConfigureAfter({DataSourceAutoConfiguration.class, MybatisLanguageDriverAutoConfiguration.class})
public class MybatisAutoConfiguration implements InitializingBean {//...@Configuration@Import({AutoConfiguredMapperScannerRegistrar.class})@ConditionalOnMissingBean({MapperFactoryBean.class, MapperScannerConfigurer.class})public static class MapperScannerRegistrarNotFoundConfiguration implements InitializingBean {public MapperScannerRegistrarNotFoundConfiguration() {}public void afterPropertiesSet() {MybatisAutoConfiguration.logger.debug("Not found configuration for registering mapper bean using @MapperScan, MapperFactoryBean and MapperScannerConfigurer.");}}public static class AutoConfiguredMapperScannerRegistrar implements BeanFactoryAware, ImportBeanDefinitionRegistrar {private BeanFactory beanFactory;public AutoConfiguredMapperScannerRegistrar() {}public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {if (!AutoConfigurationPackages.has(this.beanFactory)) {MybatisAutoConfiguration.logger.debug("Could not determine auto-configuration package, automatic mapper scanning disabled.");} else {// 这里获取要扫描的包名MybatisAutoConfiguration.logger.debug("Searching for mappers annotated with @Mapper");List<String> packages = AutoConfigurationPackages.get(this.beanFactory);if (MybatisAutoConfiguration.logger.isDebugEnabled()) {packages.forEach((pkg) -> {MybatisAutoConfiguration.logger.debug("Using auto-configuration base package '{}'", pkg);});}// 下面这些代码主要就是定义一个bean的定义,添加到BeanFactory中 BeanDefinitionBuilderBeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(MapperScannerConfigurer.class);builder.addPropertyValue("processPropertyPlaceHolders", true);// 这就是要扫描的注解类型,就是@Mapperbuilder.addPropertyValue("annotationClass", Mapper.class);// //这里是要扫描的包的路径builder.addPropertyValue("basePackage", StringUtils.collectionToCommaDelimitedString(packages));BeanWrapper beanWrapper = new BeanWrapperImpl(MapperScannerConfigurer.class);Set<String> propertyNames = (Set)Stream.of(beanWrapper.getPropertyDescriptors()).map(FeatureDescriptor::getName).collect(Collectors.toSet());if (propertyNames.contains("lazyInitialization")) {builder.addPropertyValue("lazyInitialization", "${mybatis.lazy-initialization:false}");}if (propertyNames.contains("defaultScope")) {builder.addPropertyValue("defaultScope", "${mybatis.mapper-default-scope:}");}registry.registerBeanDefinition(MapperScannerConfigurer.class.getName(), builder.getBeanDefinition());}}public void setBeanFactory(BeanFactory beanFactory) {this.beanFactory = beanFactory;}}
}

AutoConfiguredMapperScannerRegistrar主要就是把MapperScannerConfigurer这个类注册到spring中,来看MapperScannerConfigurer的代码:

public class MapperScannerConfigurer implements BeanDefinitionRegistryPostProcessor, InitializingBean, ApplicationContextAware, BeanNameAware {//...@Overridepublic void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) {if (this.processPropertyPlaceHolders) {//这个是主要设置一些属性,比如上面包名,要扫描的注解类名称等等processPropertyPlaceHolders();}//这个类看名字都知道是干什么的, 主要就是扫描mapper注解的类ClassPathMapperScanner scanner = new ClassPathMapperScanner(registry);scanner.setAddToConfig(this.addToConfig);scanner.setAnnotationClass(this.annotationClass);scanner.setMarkerInterface(this.markerInterface);scanner.setSqlSessionFactory(this.sqlSessionFactory);scanner.setSqlSessionTemplate(this.sqlSessionTemplate);scanner.setSqlSessionFactoryBeanName(this.sqlSessionFactoryBeanName);scanner.setSqlSessionTemplateBeanName(this.sqlSessionTemplateBeanName);scanner.setResourceLoader(this.applicationContext);scanner.setBeanNameGenerator(this.nameGenerator);scanner.registerFilters();scanner.scan(StringUtils.tokenizeToStringArray(this.basePackage, ConfigurableApplicationContext.CONFIG_LOCATION_DELIMITERS));}// ...
}

由于MapperScannerConfigurer这个类实现了BeanDefinitionRegistryPostProcessor,所以它就会被生成bean之前加载,调用它的postProcessBeanDefinitionRegistry方法,postProcessBeanDefinitionRegistry里面就会scan我们指定的package里的@Mapper类。再来看ClassPathMapperScanner:

public class ClassPathMapperScanner extends ClassPathBeanDefinitionScanner {//...@Overridepublic Set<BeanDefinitionHolder> doScan(String... basePackages) {Set<BeanDefinitionHolder> beanDefinitions = super.doScan(basePackages);if (beanDefinitions.isEmpty()) {logger.warn("No MyBatis mapper was found in '" + Arrays.toString(basePackages) + "' package. Please check your configuration.");} else {processBeanDefinitions(beanDefinitions);}return beanDefinitions;}private void processBeanDefinitions(Set<BeanDefinitionHolder> beanDefinitions) {GenericBeanDefinition definition;for (BeanDefinitionHolder holder : beanDefinitions) {definition = (GenericBeanDefinition) holder.getBeanDefinition();if (logger.isDebugEnabled()) {logger.debug("Creating MapperFactoryBean with name '" + holder.getBeanName() + "' and '" + definition.getBeanClassName() + "' mapperInterface");}// the mapper interface is the original class of the bean// but, the actual class of the bean is MapperFactoryBean//这里是给bean定义的添加一个构造方法参数,就是我们扫描出来mapper注解类的类名definition.getConstructorArgumentValues().addGenericArgumentValue(definition.getBeanClassName()); // issue #59// 这个就是设置对应bean的类的类,这里设置成了org.mybatis.spring.mapper.MapperFactoryBean这个类,这注意这个类实现了FactoryBean接口definition.setBeanClass(this.mapperFactoryBean.getClass());definition.getPropertyValues().add("addToConfig", this.addToConfig);boolean explicitFactoryUsed = false;if (StringUtils.hasText(this.sqlSessionFactoryBeanName)) {definition.getPropertyValues().add("sqlSessionFactory", new RuntimeBeanReference(this.sqlSessionFactoryBeanName));explicitFactoryUsed = true;} else if (this.sqlSessionFactory != null) {definition.getPropertyValues().add("sqlSessionFactory", this.sqlSessionFactory);explicitFactoryUsed = true;}if (StringUtils.hasText(this.sqlSessionTemplateBeanName)) {if (explicitFactoryUsed) {logger.warn("Cannot use both: sqlSessionTemplate and sqlSessionFactory together. sqlSessionFactory is ignored.");}definition.getPropertyValues().add("sqlSessionTemplate", new RuntimeBeanReference(this.sqlSessionTemplateBeanName));explicitFactoryUsed = true;} else if (this.sqlSessionTemplate != null) {if (explicitFactoryUsed) {logger.warn("Cannot use both: sqlSessionTemplate and sqlSessionFactory together. sqlSessionFactory is ignored.");}definition.getPropertyValues().add("sqlSessionTemplate", this.sqlSessionTemplate);explicitFactoryUsed = true;}if (!explicitFactoryUsed) {if (logger.isDebugEnabled()) {logger.debug("Enabling autowire by type for MapperFactoryBean with name '" + holder.getBeanName() + "'.");}definition.setAutowireMode(AbstractBeanDefinition.AUTOWIRE_BY_TYPE);}}}//...
}

最终在获取bean的时候,会调用MapperFactoryBean这个类的getObject()

public class MapperFactoryBean<T> extends SqlSessionDaoSupport implements FactoryBean<T> {private Class<T> mapperInterface;// ...public MapperFactoryBean(Class<T> mapperInterface) {this.mapperInterface = mapperInterface;}/*** {@inheritDoc}*/@Overridepublic T getObject() throws Exception {return getSqlSession().getMapper(this.mapperInterface);}/*** {@inheritDoc}*/@Overridepublic Class<T> getObjectType() {return this.mapperInterface;}//....
}

getObject()里会返回代理对象,对象的类型即 构造函数里传进来的 mapperInterface 。

的加载,beanFatory加载@Mapper类

相关文章:

Mybatis在SpringBoot中是如何被加载执行

首先依赖于springboot的自动装配EnableAutoConfiguration注解&#xff0c;这个注解最终帮助我们读取mybatis-spring-boot-autoconfigure-x.x.x.jar中的META-INF\spring.factories配置类&#xff1a; org.springframework.boot.autoconfigure.EnableAutoConfiguration\ org.myb…...

数据采集用,集成了主流工业通讯协议

IoTClient 是一个物联网设备通讯协议实现客户端&#xff0c;集成了主流工业通讯协议&#xff0c;包括主流PLC通信读取、ModBus协议、Bacnet协议等。该组件基于.NET Standard 2.0&#xff0c;适用于.NET的跨平台开发&#xff0c;可在Windows、Linux等系统上运行&#xff0c;甚至…...

Django(三)-搭建第一个应用(2)

一、编写更多视图 问题详情页——展示某个投票的问题和不带结果的选项列表。问题结果页——展示某个投票的结果。投票处理器——用于响应用户为某个问题的特定选项投票的操作。 # 1.问题详情页&#xff1a;展示某个投票的问题和不带结果的选项列表 def detail(request,questi…...

求助:配置脚手架代理,跨域问题proxyTable配置无效,访问后显示404?

已经在这里卡了一天了。找了很多解决办法&#xff0c;比如重启&#xff0c;修改proxytable等等&#xff0c;但是每次但是404&#xff0c;求助各位大佬&#xff0c;怎么解决&#xff1f; 1、代码 &#xff08;1&#xff09;config的index.js &#xff08;2&#xff09; App.v…...

【4月】组队打卡《山有木Python特征工程极简入门》

活动名称 CDA Club 第2期《山有木兮Python数据分析极简入门》组队打卡 活动介绍 本次打卡活动由CDA俱乐部旗下学术部主办。目的是通过数据分析科普内容&#xff0c;为数据分析爱好者提供学习和交流的机会。方便大家利用碎片化时间在线学习&#xff0c;以组队打卡的形式提升学…...

Wireshark 抓包

启动时选择一个有信号的网卡双击打开&#xff0c;或者在 捕获选择里打开选择网卡。 然后输出下面的规则就可以抓到报文了。 最上面的三条是建立连接时的三次握手&#xff0c; 下面是发送数据hello 对应两条数据 最下面的4条是断时的4次挥手...

c语言运算符优先级

1、运算符介绍 在C语言中&#xff0c;运算符优先级是指在表达式中执行运算的先后顺序。按照C语言的标准规范&#xff0c;不同的运算符被赋予了不同的优先级等级&#xff0c;优先级高的运算符会先进行运算。如果同一优先级的运算符出现在同一个表达式中&#xff0c;则按照从左到…...

纳斯达克大屏媒体尺寸与投放费用:一次投放需要多少钱?

纳斯达克大屏媒体尺寸与投放费用&#xff1a;一次投放需要多少钱&#xff1f; 1. 纳斯达克图片要求 1.1 像素要求 高度&#xff1a;2336 像素宽度&#xff1a;1832 像素 1.2 分辨率要求 像素比率&#xff1a;1.0 px 72 dpi 1.3 文件格式要求 静态图片格式&#xff1a;.…...

将word转为PDF的几种简单方式

第一种&#xff1a;使用spire.doc.jar包&#xff0c;用时7秒左右。 引入spire.doc-11.1.1.jar包&#xff0c;该包带水印&#xff0c;建议使用免费版的spire.doc.free-5.2.0.jar&#xff0c;免费版只能转三页。 package web.tools.excel; import com.spire.doc.*; public cl…...

大型集团公司企业文化知识竞活动赛策划方案

一场高端企业文化知识竞赛活动完整策划书&#xff0c;按诗词大会舞美标准进行设计&#xff0c;竞赛规则新颖&#xff0c;值得收藏。 天纵高端知识竞赛服务商&#xff0c;20多年现场经验和软硬件开发。 专业承办全国高端知识竞赛活动。线上线下各类竞赛活动均可执行&#xff0c;…...

Spring Boot设置io临时目录

在部署springboot项目&#xff0c;使用MultipartFile上传文件会出现以下异常 Failed to parse multipart servlet request; nested exception is java.io.IOException: The temporary upload location [/tmp/tomcat.3016596448718765136.18001/work/Tomcat/localhost/xx] is …...

Polar 2024春季个人挑战赛 Jay17 WP

Polar 2024春季个人挑战赛 Rank&#xff1a;7 【WEB】机器人 开题 起手敏感文件robots.txt 【WEB】PHP反序列化初试 最简单的php反序列化 POC&#xff1a; <?php class Easy{public $name;public function __wakeup(){echo $this->name;} } class Evil{public $evi…...

10 mybatis 日志

文章目录 product.sqlpom.xmllogback.xmlmybatis-config.xmlProductsMapper.xmlProductsProductsMapper.java product.sql create table products (product_id int auto_increment comment 产品IDprimary key,product_name varchar(100) null comment 产品名称,bra…...

AJAX介绍使用案例

文章目录 一、AJAX概念二、AJAX快速入门1、编写AjaxServlet&#xff0c;并使用response输出字符&#xff08;后台代码&#xff09;2、创建XMLHttpRequest对象&#xff1a;用于和服务器交换数据 & 3、向服务器发送请求 & 4、获取服务器响应数据 三、案例-验证用户是否存…...

【echart】数据可视化

什么是数据可视化&#xff1f; 数据可视化主要目的:借助于图形化手段&#xff0c;清晰有效地传达与沟通信息。 数据可视化可以把数据从冰冷的数字转换成图形&#xff0c;揭示蕴含在数据中的规律和道理。 如何绘制&#xff1f; echarts 图表的绘制&#xff0c;大体分为三步:…...

排序(冒泡/快速/归并)

冒泡排序 时间复杂度为 O(n^2) 原理 比较相邻的元素. 如果第一个比第二个大,就交换他们两个.依次比较每一对相邻的元素—>结果 : 最后的元素是这组数中最大的重复上述步骤 , 除了最后一个[]因为最后一个已经是排好序的了(这组数中最大的那个)]持续对越来越少的元素进行如上…...

jq中的跨域

跨域 1.从一个地址到另外一个第一请求资源或者数据时&#xff0c;就有可能发生跨域 <!DOCTYPE html> <html lang"en"> <head><meta charset"UTF-8"><title>跨域</title><script src"jquery/jquery-1.11.3.j…...

CUDA学习笔记08: 原子规约/向量求和

参考资料 CUDA编程模型系列一(核心函数)_哔哩哔哩_bilibili 代码 #include <iostream> #include <cuda_runtime.h> #include <device_launch_parameters.h> #include <stdio.h> #include <math.h>#define N 10000000 #define BLOCK 256 #def…...

PointNet++论文复现(一)【PontNet网络模型代码详解 - 分类部分】

PontNet网络模型代码详解 - 分类部分 专栏持续更新中!关注博主查看后续部分! 分类模型的训练: ## e.g., pointnet2_ssg without normal features python train_classification.py --model pointnet2_cls_ssg --log_dir pointnet2_cls_ssg python test_classification.py…...

AI渣土车监测报警摄像机

随着城市建设的不断发展和交通运输的快速增长&#xff0c;渣土车作为建筑行业中不可或缺的运输工具&#xff0c;承担着大量的渣土运输任务。然而&#xff0c;由于渣土车在运输过程中存在超速、违规变道、碾压行人等交通安全问题&#xff0c;给道路交通和行人安全带来了严重的隐…...

UE5 学习系列(二)用户操作界面及介绍

这篇博客是 UE5 学习系列博客的第二篇&#xff0c;在第一篇的基础上展开这篇内容。博客参考的 B 站视频资料和第一篇的链接如下&#xff1a; 【Note】&#xff1a;如果你已经完成安装等操作&#xff0c;可以只执行第一篇博客中 2. 新建一个空白游戏项目 章节操作&#xff0c;重…...

C++_核心编程_多态案例二-制作饮品

#include <iostream> #include <string> using namespace std;/*制作饮品的大致流程为&#xff1a;煮水 - 冲泡 - 倒入杯中 - 加入辅料 利用多态技术实现本案例&#xff0c;提供抽象制作饮品基类&#xff0c;提供子类制作咖啡和茶叶*//*基类*/ class AbstractDr…...

VM虚拟机网络配置(ubuntu24桥接模式):配置静态IP

编辑-虚拟网络编辑器-更改设置 选择桥接模式&#xff0c;然后找到相应的网卡&#xff08;可以查看自己本机的网络连接&#xff09; windows连接的网络点击查看属性 编辑虚拟机设置更改网络配置&#xff0c;选择刚才配置的桥接模式 静态ip设置&#xff1a; 我用的ubuntu24桌…...

【分享】推荐一些办公小工具

1、PDF 在线转换 https://smallpdf.com/cn/pdf-tools 推荐理由&#xff1a;大部分的转换软件需要收费&#xff0c;要么功能不齐全&#xff0c;而开会员又用不了几次浪费钱&#xff0c;借用别人的又不安全。 这个网站它不需要登录或下载安装。而且提供的免费功能就能满足日常…...

排序算法总结(C++)

目录 一、稳定性二、排序算法选择、冒泡、插入排序归并排序随机快速排序堆排序基数排序计数排序 三、总结 一、稳定性 排序算法的稳定性是指&#xff1a;同样大小的样本 **&#xff08;同样大小的数据&#xff09;**在排序之后不会改变原始的相对次序。 稳定性对基础类型对象…...

uni-app学习笔记三十五--扩展组件的安装和使用

由于内置组件不能满足日常开发需要&#xff0c;uniapp官方也提供了众多的扩展组件供我们使用。由于不是内置组件&#xff0c;需要安装才能使用。 一、安装扩展插件 安装方法&#xff1a; 1.访问uniapp官方文档组件部分&#xff1a;组件使用的入门教程 | uni-app官网 点击左侧…...

结构化文件管理实战:实现目录自动创建与归类

手动操作容易因疲劳或疏忽导致命名错误、路径混乱等问题&#xff0c;进而引发后续程序异常。使用工具进行标准化操作&#xff0c;能有效降低出错概率。 需要快速整理大量文件的技术用户而言&#xff0c;这款工具提供了一种轻便高效的解决方案。程序体积仅有 156KB&#xff0c;…...

第22节 Node.js JXcore 打包

Node.js是一个开放源代码、跨平台的、用于服务器端和网络应用的运行环境。 JXcore是一个支持多线程的 Node.js 发行版本&#xff0c;基本不需要对你现有的代码做任何改动就可以直接线程安全地以多线程运行。 本文主要介绍JXcore的打包功能。 JXcore 安装 下载JXcore安装包&a…...

在ubuntu等linux系统上申请https证书

使用 Certbot 自动申请 安装 Certbot Certbot 是 Let’s Encrypt 官方推荐的自动化工具&#xff0c;支持多种操作系统和服务器环境。 在 Ubuntu/Debian 上&#xff1a; sudo apt update sudo apt install certbot申请证书 纯手动方式&#xff08;不自动配置&#xff09;&…...

JS设计模式(5): 发布订阅模式

解锁JavaScript发布订阅模式&#xff1a;让代码沟通更优雅 在JavaScript的世界里&#xff0c;我们常常会遇到这样的场景&#xff1a;多个模块之间需要相互通信&#xff0c;但是又不想让它们产生过于紧密的耦合。这时候&#xff0c;发布订阅模式就像一位优雅的信使&#xff0c;…...