Spring系列之Mybatis动态代理实现全过程?回答正确率不到1%
面试中,可能会问到Spring怎么绑定Mapper接口和SQL语句的。一般的答案是Spring会为Mapper生成一个代理类,调用的时候实际调用的是代理类的实现。但是如果被追问代理类实现的细节,很多同学会卡壳,今天借助2张图来阅读一下代码如何实现的。
一、代理工厂类生成的过程
步骤1
在启动类上加上注解MapperScan
@SpringBootApplication
@MapperScan(basePackages = "com.example.springdatasourcedruid.dal")
public class SpringDatasourceDruidApplication {
public static void main(String[] args) {
SpringApplication.run(SpringDatasourceDruidApplication.class, args);
}
}
步骤2
/**
*指定mapper接口所在的包,然后包下面的所有接口在编译之后都会生成相应的实现类
*这个注解引入了MapperScannerRegistrar类
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Documented
@Import(MapperScannerRegistrar.class)
@Repeatable(MapperScans.class)
public @interface MapperScan {
//扫描的包路径列表
String[] basePackages() default {};
//代理工厂类类型
Class<? extends MapperFactoryBean> factoryBean() default MapperFactoryBean.class;
//作用范围,这里默认是单例
String defaultScope() default AbstractBeanDefinition.SCOPE_DEFAULT;
}
步骤3、4
实现ImportBeanDefinitionRegistrar接口,目的是实现动态创建自定义的bean
public class MapperScannerRegistrar implements ImportBeanDefinitionRegistrar, ResourceLoaderAware {
//Spring 会回调该方法
@Override
public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
//获取MapperScan注解设置的全部属性信息
AnnotationAttributes mapperScanAttrs = AnnotationAttributes
.fromMap(importingClassMetadata.getAnnotationAttributes(MapperScan.class.getName()));
if (mapperScanAttrs != null) {
//调用具体的实现
registerBeanDefinitions(importingClassMetadata, mapperScanAttrs, registry,
generateBaseBeanName(importingClassMetadata, 0));
}
}
//注册一个 BeanDefinition ,这里会构建并且向容器中注册一个bd 也就是一个自定义的扫描器 MapperScannerConfigurer
//mapperFactoryBeanClass的类型MapperFactoryBean
void registerBeanDefinitions(AnnotationMetadata annoMeta, AnnotationAttributes annoAttrs,
BeanDefinitionRegistry registry, String beanName) {
//构建一个 BeanDefinition 他的实例对象是 MapperScannerConfigurer
BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(MapperScannerConfigurer.class);
builder.addPropertyValue("processPropertyPlaceHolders", true);
Class<? extends MapperFactoryBean> mapperFactoryBeanClass = annoAttrs.getClass("factoryBean");
if (!MapperFactoryBean.class.equals(mapperFactoryBeanClass)) {
builder.addPropertyValue("mapperFactoryBeanClass", mapperFactoryBeanClass);
}
registry.registerBeanDefinition(beanName, builder.getBeanDefinition());
}
}
步骤5
将MapperScannerConfigurer注册到beanFactory,MapperScannerConfigurer是为了解决MapperFactoryBean繁琐而生的,有了MapperScannerConfigurer就不需要我们去为每个映射接口去声明一个bean了。大大缩减了开发的效率
步骤6、7
回调postProcessBeanDefinitionRegistry方法,目的是初始化扫描器,并且回调扫描basePackages下的接口,获取到所有符合条件的记录
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) {
if (this.processPropertyPlaceHolders) {
processPropertyPlaceHolders();
}
//初始化扫描器,可以扫描项目下的class文件转换成BeanDefinition
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.setMapperFactoryBeanClass(this.mapperFactoryBeanClass);
if (StringUtils.hasText(lazyInitialization)) {
scanner.setLazyInitialization(Boolean.valueOf(lazyInitialization));
}
if (StringUtils.hasText(defaultScope)) {
scanner.setDefaultScope(defaultScope);
}
//这一步是很重要的,他是注册了一系列的过滤器,使得Spring在扫描到Mapper接口的时候不被过滤掉
scanner.registerFilters();
//执行扫描
scanner.scan(
StringUtils.tokenizeToStringArray(this.basePackage, ConfigurableApplicationContext.CONFIG_LOCATION_DELIMITERS));
}
步骤8、9
将Mapper接口的实现设置为MapperFactoryBean,并且注册到容器中,后面其他类依赖注入首先获取到的是MapperFactoryBean
private void processBeanDefinitions(Set<BeanDefinitionHolder> beanDefinitions) {
AbstractBeanDefinition definition;
BeanDefinitionRegistry registry = getRegistry();
for (BeanDefinitionHolder holder : beanDefinitions) {
definition = (AbstractBeanDefinition) holder.getBeanDefinition();
String beanClassName = definition.getBeanClassName();
definition.getConstructorArgumentValues().addGenericArgumentValue(beanClassName); // issue #59
//将对应的Mapper接口,设置为MapperFactoryBean
definition.setBeanClass(this.mapperFactoryBeanClass);
definition.getPropertyValues().add("addToConfig", this.addToConfig);
//-------忽略了非关键代码--------------------------------
//将Mapper接口注册到BeanDefinition,这时候实际的实现类已经被指定为MapperFactoryBean
registry.registerBeanDefinition(proxyHolder.getBeanName(), proxyHolder.getBeanDefinition());
}
}
二、代理类的生成以及使用
我们根据上面的情况已经知道,实际在容器中保存的是MapperFactoryBean,这里也并不没有和SQL关联上,实际在依赖注入的时候,还会进行加工,获取到真正的代理类,在下面的图中进一步解释。
步骤1
在xxxService用注解@Autowired(@Resource)、构造方法方式引入xxxMapper属性
步骤2
通过调用AbstractBeanFactory.getBean方法获取bean,此为方法入口
public <T> T getBean(String name, Class<T> requiredType) throws BeansException {
return this.doGetBean(name, requiredType, (Object[])null, false);
}
步骤3
因为容器中存在是MapperFactoryBean,所以后续是调用MapperFactoryBean.getObject方法,SqlSessionDaoSupport类中getSqlSession实际返回的是sqlSessionTemplate
public class MapperFactoryBean<T> extends SqlSessionDaoSupport implements FactoryBean<T> {
@Override
public T getObject() throws Exception {
return getSqlSession().getMapper(this.mapperInterface);
}
}
步骤4
调用sqlSessionTemplate.getMapper,getConfiguration()获取到的对象就是Configuration
@Override
public <T> T getMapper(Class<T> type) {
return getConfiguration().getMapper(type, this);
}
步骤5
调用Configuration.getMapper方法
public <T> T getMapper(Class<T> type, SqlSession sqlSession) {
return this.mapperRegistry.getMapper(type, sqlSession);
}
步骤6
调用MapperRegistry.getMapper方法,这里先从缓存中获取MapperProxyFactory,然后再生成相应的实例
public <T> T getMapper(Class<T> type, SqlSession sqlSession) {
MapperProxyFactory<T> mapperProxyFactory = (MapperProxyFactory)this.knownMappers.get(type);
if (mapperProxyFactory == null) {
throw new BindingException("Type " + type + " is not known to the MapperRegistry.");
} else {
try {
return mapperProxyFactory.newInstance(sqlSession);
} catch (Exception var5) {
throw new BindingException("Error getting mapper instance. Cause: " + var5, var5);
}
}
}
步骤7、8
调用java动态代理类生成代理对象MapperProxy,并且返回
protected T newInstance(MapperProxy<T> mapperProxy) {
return Proxy.newProxyInstance(this.mapperInterface.getClassLoader(), new Class[]{this.mapperInterface}, mapperProxy);
}
public T newInstance(SqlSession sqlSession) {
MapperProxy<T> mapperProxy = new MapperProxy(sqlSession, this.mapperInterface, this.methodCache);
return this.newInstance(mapperProxy);
}
步骤9
将xxxMapper设置到xxxService完成属性注入
三、使用Mapper的过程
比如说我们要调用xxxMapper.insert方法
步骤1
上面讲到我们实际注入的是动态代理对象MapperProxy,因此实际调用的是MapperProxy.invoke方法,依据代码我们很容易得出后续走的方法是cachedInvoker.invoke,proxy即使MapperProxy对象,method即insert方法,args即为传入要插入的实体对象
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
try {
return Object.class.equals(method.getDeclaringClass()) ? method.invoke(this, args) : this.cachedInvoker(method).invoke(proxy, method, args, this.sqlSession);
} catch (Throwable var5) {
throw ExceptionUtil.unwrapThrowable(var5);
}
}
因insert不是默认方法,因此执行的逻辑是 MapperProxy.PlainMethodInvoke
private MapperProxy.MapperMethodInvoker cachedInvoker(Method method) throws Throwable {
try {
return (MapperProxy.MapperMethodInvoker)MapUtil.computeIfAbsent(this.methodCache, method, (m) -> {
if (m.isDefault()) {
try {
return privateLookupInMethod == null ? new MapperProxy.DefaultMethodInvoker(this.getMethodHandleJava8(method)) : new MapperProxy.DefaultMethodInvoker(this.getMethodHandleJava9(method));
} catch (InstantiationException | InvocationTargetException | NoSuchMethodException | IllegalAccessException var4) {
throw new RuntimeException(var4);
}
} else {
//如果不是默认方法,执行该段逻辑
return new MapperProxy.PlainMethodInvoker(new MapperMethod(this.mapperInterface, method, this.sqlSession.getConfiguration()));
}
});
} catch (RuntimeException var4) {
Throwable cause = var4.getCause();
throw (Throwable)(cause == null ? var4 : cause);
}
}
步骤2
执行PlainMethodInvoker.invoke方法
public Object invoke(Object proxy, Method method, Object[] args, SqlSession sqlSession) throws Throwable {
return this.mapperMethod.execute(sqlSession, args);
}
步骤3
这里才是真正和SQL相关的部分,方法的类型是根据xml文件中节点名称获取的,不如我们的例子中是insert,这里对应的就是case INSERT,后续的调用就是sqlSession和数据库的关联了
public Object execute(SqlSession sqlSession, Object[] args) {
Object result;
Object param;
switch(this.command.getType()) {
case INSERT:
param = this.method.convertArgsToSqlCommandParam(args);
result = this.rowCountResult(sqlSession.insert(this.command.getName(), param));
break;
case UPDATE:
param = this.method.convertArgsToSqlCommandParam(args);
result = this.rowCountResult(sqlSession.update(this.command.getName(), param));
break;
case DELETE:
param = this.method.convertArgsToSqlCommandParam(args);
result = this.rowCountResult(sqlSession.delete(this.command.getName(), param));
break;
case SELECT:
if (this.method.returnsVoid() && this.method.hasResultHandler()) {
this.executeWithResultHandler(sqlSession, args);
result = null;
} else if (this.method.returnsMany()) {
result = this.executeForMany(sqlSession, args);
} else if (this.method.returnsMap()) {
result = this.executeForMap(sqlSession, args);
} else if (this.method.returnsCursor()) {
result = this.executeForCursor(sqlSession, args);
} else {
param = this.method.convertArgsToSqlCommandParam(args);
result = sqlSession.selectOne(this.command.getName(), param);
if (this.method.returnsOptional() && (result == null || !this.method.getReturnType().equals(result.getClass()))) {
result = Optional.ofNullable(result);
}
}
break;
case FLUSH:
result = sqlSession.flushStatements();
break;
default:
throw new BindingException("Unknown execution method for: " + this.command.getName());
}
if (result == null && this.method.getReturnType().isPrimitive() && !this.method.returnsVoid()) {
throw new BindingException("Mapper method '" + this.command.getName() + " attempted to return null from a method with a primitive return type (" + this.method.getReturnType() + ").");
} else {
return result;
}
}
四、总结
这里基本上从代理工厂类的生成、代理类的生成、以及使用的过程,结合上面两幅图和代码,相信你已经有了充分的了解。
关注我,一起成长和进步,下一篇继续
Spring系列之Mybatis动态代理实现全过程?回答正确率不到1%的更多相关文章
- Spring事务Transactional和动态代理(二)-cglib动态代理
系列文章索引: Spring事务Transactional和动态代理(一)-JDK代理实现 Spring事务Transactional和动态代理(二)-cglib动态代理 Spring事务Transa ...
- Java EE开发平台随手记5——Mybatis动态代理接口方式的原生用法
为了说明后续的Mybatis扩展,插播一篇广告,先来简要说明一下Mybatis的一种原生用法,不过先声明:下面说的只是Mybatis的其中一种用法,如需要更深入了解Mybatis,请参考官方文档,或者 ...
- 通过模拟Mybatis动态代理生成Mapper代理类,讲解Mybatis核心原理
本文将通过模拟Mybatis动态代理生成Mapper代理类,讲解Mybatis原理 1.平常我们是如何使用Mapper的 先写一个简单的UserMapper,它包含一个全表查询的方法,代码如下 pub ...
- MyBatis 动态代理开发
MyBatis 动态代理开发 § Mapper.xml文件中的namespace与mapper接口的类路径相同. § Mapper接口方法名和Mapper.xml中定义的每个statement的i ...
- Spring事务Transactional和动态代理(一)-JDK代理实现
系列文章索引: Spring事务Transactional和动态代理(一)-JDK代理实现 Spring事务Transactional和动态代理(二)-cglib动态代理 Spring事务Transa ...
- Spring事务Transactional和动态代理(三)-事务失效的场景
系列文章索引: Spring事务Transactional和动态代理(一)-JDK代理实现 Spring事务Transactional和动态代理(二)-cglib动态代理 Spring事务Transa ...
- Spring中的cglib动态代理
Spring中的cglib动态代理 cglib:Code Generation library, 基于ASM(java字节码操作码)的高性能代码生成包 被许多AOP框架使用 区别于JDK动态代理,cg ...
- Spring中的JDK动态代理
Spring中的JDK动态代理 在JDK1.3以后提供了动态代理的技术,允许开发者在运行期创建接口的代理实例.在Sun刚推出动态代理时,还很难想象它有多大的实际用途,现在动态代理是实现AOP的绝好底层 ...
- Spring AOP中的动态代理
0 前言 1 动态代理 1.1 JDK动态代理 1.2 CGLIB动态代理 1.2.1 CGLIB的代理用法 1.2.2 CGLIB的过滤功能 2 Spring AOP中的动态代理机制 2.1 ...
随机推荐
- Node.js躬行记(7)——定时任务的进化史
一.纯手工 公司主营的是直播业务,会很许多打榜活动,也就是按主播收到的礼物或收益进行排序,排在前面的会有相应奖励. 纯手工时代,每接到一个活动,就重新写一份,第一次写完.之后就是复制黏贴,再修改,每次 ...
- Synology群晖100TB万兆文件云服务器NAS存储池类别 RAID 6 (有数据保护)2021年7月29日 - Copy
Synology群晖100TB万兆文件云服务器NAS存储池类别 RAID 6 (有数据保护)2021年7月29日 - Copy https://www.autoahk.com/archives/367 ...
- centos7 安装mariadb、"systemctl status mariadb.service" and "journalctl -xe" for details
centos7 mariadb 安装 也可解决此错误:ob for mariadb.service failed because the control process exited with err ...
- LeetCode通关:哈希表六连,这个还真有点简单
精品刷题路线参考: https://github.com/youngyangyang04/leetcode-master https://github.com/chefyuan/algorithm-b ...
- GitHub标星8k,字节跳动高工熬夜半月整理的“组件化实战学习手册”,全是精髓!
前言 什么是组件化? 最初的目的是代码重用,功能相对单一或者独立.在整个系统的代码层次上位于最底层,被其他代码所依赖,所以说组件化是纵向分层. 为什么要使用组件化? 当我们的项目越做越大的时候,有时间 ...
- webservice接口调用
package com.montnets.emp.sysuser.biz; import org.apache.axis.client.Call; import org.apache.axis.cli ...
- JmoVxia
关于我 网名:季末微夏 英文:JmoVxia 签名:路漫漫其修远兮,吾将上下而求索 标签:iOS开发(ma)工程师(nong).技术爱好者 联系我 邮箱:JmoVxia@gmail.com Githu ...
- pikachu Unsafe Filedownload 不安全的文件下载
不安全的文件下载概述文件下载功能在很多web系统上都会出现,一般我们当点击下载链接,便会向后台发送一个下载请求,一般这个请求会包含一个需要下载的文件名称,后台在收到请求后 会开始执行下载代码,将该文件 ...
- Android 9.0 默认输入法的设置流程分析
Android 输入法设置文章 Android 9.0 默认输入法的设置流程分析 Android 9.0 添加预置第三方输入法/设置默认输入法(软键盘) 前言 在上一篇文章 Android 9.0 ...
- webGis概念
参考:https://blog.csdn.net/qq_36375770/article/details/80077533 参考:https://blog.csdn.net/BuquTianya/ar ...