mybatis-spring @MapperScan走读分析

ops/2025/1/15 5:44:36/

接上一篇文章:https://blog.csdn.net/qq_26437925/article/details/145100531, 本文注解分析mybatis-spring中的@MapperScan注解,则将容易许多。

目录

    • @MapperScan注解定义
    • ConfigurationClassPostProcessor扫描注册beanDefinition
    • org.mybatis.spring.mapper.MapperFactoryBean
    • org.apache.ibatis.binding.MapperProxy
      • org.apache.ibatis.executor.SimpleExecutor#doUpdate
    • 总结

@MapperScan注解定义

@MapperScan注解加入了@Import(MapperScannerRegistrar.class), 所以可以知晓

java">@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Documented
@Import(MapperScannerRegistrar.class)
public @interface MapperScan {/*** Alias for the {@link #basePackages()} attribute. Allows for more concise* annotation declarations e.g.:* {@code @EnableMyBatisMapperScanner("org.my.pkg")} instead of {@code* @EnableMyBatisMapperScanner(basePackages= "org.my.pkg"})}.*/String[] value() default {};/*** Base packages to scan for MyBatis interfaces. Note that only interfaces* with at least one method will be registered; concrete classes will be* ignored.*/String[] basePackages() default {};/*** Type-safe alternative to {@link #basePackages()} for specifying the packages* to scan for annotated components. The package of each class specified will be scanned.* <p>Consider creating a special no-op marker class or interface in each package* that serves no purpose other than being referenced by this attribute.*/Class<?>[] basePackageClasses() default {};/*** The {@link BeanNameGenerator} class to be used for naming detected components* within the Spring container.*/Class<? extends BeanNameGenerator> nameGenerator() default BeanNameGenerator.class;/*** This property specifies the annotation that the scanner will search for.* <p>* The scanner will register all interfaces in the base package that also have* the specified annotation.* <p>* Note this can be combined with markerInterface.*/Class<? extends Annotation> annotationClass() default Annotation.class;/*** This property specifies the parent that the scanner will search for.* <p>* The scanner will register all interfaces in the base package that also have* the specified interface class as a parent.* <p>* Note this can be combined with annotationClass.*/Class<?> markerInterface() default Class.class;/*** Specifies which {@code SqlSessionTemplate} to use in the case that there is* more than one in the spring context. Usually this is only needed when you* have more than one datasource.*/String sqlSessionTemplateRef() default "";/*** Specifies which {@code SqlSessionFactory} to use in the case that there is* more than one in the spring context. Usually this is only needed when you* have more than one datasource.*/String sqlSessionFactoryRef() default "";/*** Specifies a custom MapperFactoryBean to return a mybatis proxy as spring bean.**/Class<? extends MapperFactoryBean> factoryBean() default MapperFactoryBean.class;}

ConfigurationClassPostProcessor扫描注册beanDefinition

mybatis-spring中自定义了org.mybatis.spring.annotation.MapperScannerRegistrar实现了ImportBeanDefinitionRegistrar接口,所以能被处理

在这里插入图片描述
mybatis-spring也实现了自己的Scanner能够扫描出所有的@Mapper的interface, 然后定义出BeanDefinition

继续debug可以看到对BeanDefinisiton 会设置BeanClass为FactoryBean类在这里插入图片描述

即自定义的org.mybatis.spring.mapper.MapperFactoryBean

mybatisspringmapperMapperFactoryBean_101">org.mybatis.spring.mapper.MapperFactoryBean

仍然是重点关注getObject方法

java">@Override
public T getObject() throws Exception {return getSqlSession().getMapper(this.mapperInterface);
}

数据库操作也封装为SqlSession接口,有多个实现类可选择
在这里插入图片描述

最后也会发现是java 动态代理
在这里插入图片描述

org.apache.ibatis.binding.MapperProxy

代理的具体实现则在mybatis依赖的MapperProxy类中

java">@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {try {if (Object.class.equals(method.getDeclaringClass())) {return method.invoke(this, args);} else if (isDefaultMethod(method)) {return invokeDefaultMethod(proxy, method, args);}} catch (Throwable t) {throw ExceptionUtil.unwrapThrowable(t);}final MapperMethod mapperMethod = cachedMapperMethod(method);return mapperMethod.execute(sqlSession, args);
}

sql执行

java">public Object execute(SqlSession sqlSession, Object[] args) {Object result;switch (command.getType()) {case INSERT: {Object param = method.convertArgsToSqlCommandParam(args);result = rowCountResult(sqlSession.insert(command.getName(), param));break;}case UPDATE: {Object param = method.convertArgsToSqlCommandParam(args);result = rowCountResult(sqlSession.update(command.getName(), param));break;}case DELETE: {Object param = method.convertArgsToSqlCommandParam(args);result = rowCountResult(sqlSession.delete(command.getName(), param));break;}case SELECT:if (method.returnsVoid() && method.hasResultHandler()) {executeWithResultHandler(sqlSession, args);result = null;} else if (method.returnsMany()) {result = executeForMany(sqlSession, args);} else if (method.returnsMap()) {result = executeForMap(sqlSession, args);} else if (method.returnsCursor()) {result = executeForCursor(sqlSession, args);} else {Object param = method.convertArgsToSqlCommandParam(args);result = sqlSession.selectOne(command.getName(), param);}break;case FLUSH:result = sqlSession.flushStatements();break;default:throw new BindingException("Unknown execution method for: " + command.getName());}if (result == null && method.getReturnType().isPrimitive() && !method.returnsVoid()) {throw new BindingException("Mapper method '" + command.getName() + " attempted to return null from a method with a primitive return type (" + method.getReturnType() + ").");}return result;
}

org.apache.ibatis.executor.SimpleExecutor#doUpdate

继续深入找一个简单的sql执行实现类,可以看到类似jdbc的处理流程
在这里插入图片描述

总结

最后还是回到了上一篇博文:https://blog.csdn.net/qq_26437925/article/details/145100531。只不过mybatis-spring要丰富一些,原理仍然是动态代理BeanFactoryPostProcessorFactoryBeanBeanPostProcessor这些基础知识。


http://www.ppmy.cn/ops/150214.html

相关文章

ansible之playbook实战

环境&#xff1a; client centos server ubuntu cat pro1.yml --- - hosts: www.test.comtasks:- name: Install Httpd Serverapt: nameapache2 statepresent- name: Configurate Httpd Servercopy: content"Iam client" dest/var/www/html/index.html- name: Start…

React方向:react中5种Dom的操作方式

1、通过原生JS获取Dom去操作 通过document.querySelector(#title)原生js的方式去拿到dom节点&#xff0c;然后去进行操作。 import {Component} from "react";class App extends Component {//定义获取Dom的函数handleGetDom(){let title document.querySelector(#t…

Notepad++上NppFTP插件的安装和使用教程

一、NppFTP插件下载 图示是已经安装好了插件。 在搜索框里面搜NppFTP&#xff0c;一般情况下&#xff0c;自带的下载地址容易下载失败。这里准备了一个下载连接&#xff1a;Release v0.29.10 ashkulz/NppFTP GitHub 这里我下载的是x86版本 下载好后在nodepad的插件里面选择打…

ASP.NET Core - 依赖注入(四)

ASP.NET Core - 依赖注入&#xff08;四&#xff09; 4. ASP.NET Core默认服务5. 依赖注入配置变形 4. ASP.NET Core默认服务 之前讲了中间件&#xff0c;实际上一个中间件要正常进行工作&#xff0c;通常需要许多的服务配合进行&#xff0c;而中间件中的服务自然也是通过 Ioc…

Java学习,集合遍历

Java遍历集合&#xff08;如List, Set, Map等&#xff09;通常有多种方法。遍历集合的方式&#xff0c;包括传统for循环、增强的for循环&#xff08;也称"for-each"循环&#xff09;、迭代器&#xff08;Iterator&#xff09;以及流&#xff08;Stream&#xff09;AP…

Mysql--运维篇--备份和恢复(逻辑备份,mysqldump,物理备份,热备份,温备份,冷备份,二进制文件备份和恢复等)

MySQL 提供了多种备份方式&#xff0c;每种方式适用于不同的场景和需求。根据备份的粒度、速度、恢复时间和对数据库的影响&#xff0c;可以选择合适的备份策略。主要备份方式有三大类&#xff1a;逻辑备份&#xff08;mysqldump&#xff09;&#xff0c;物理备份和二进制文件备…

2025年三个月自学手册 网络安全(黑客技术)

&#x1f91f; 基于入门网络安全/黑客打造的&#xff1a;&#x1f449;黑客&网络安全入门&进阶学习资源包 前言 什么是网络安全 网络安全可以基于攻击和防御视角来分类&#xff0c;我们经常听到的 “红队”、“渗透测试” 等就是研究攻击技术&#xff0c;而“蓝队”、“…

MySQL 学习指南与资料分享

MySQL 学习资料 MySQL 学习资料 MySQL 学习资料 在如今数据驱动发展的大趋势下&#xff0c;MySQL 作为开源关系型数据库管理系统的佼佼者&#xff0c;广泛应用于各个领域&#xff0c;从个人博客搭建到大型电商平台的数据管理&#xff0c;它都发挥着关键作用。如果你立志掌握这…