SpringBoot 如何集成mybatis 源码分析

1.一般来说整合的思路是是什么?

加入jar包即可,那么Springboot 是如何帮我们整合的呢?

 

其中一个依赖了mybatis-spring-boot-autoconfigr.jar

在mbatis-spring-boot-autoconfigure.jar 中的sping.facotres.

在MybatisAutoConfiguration 这个类

在这个类中,注入了如下解组件:

sqlSessionFactory

和sqlSessionTemplae

@Import{{}AutoConfigureMapperScannerRegister.class}这个配置类中,又导入了

AutoConfigruationMapperScannerReister

那么导入的AutoConfigurationMapperScannerRegister干了什么呢?

public static class AutoConfiguredMapperScannerRegistrar implements BeanFactoryAware, ImportBeanDefinitionRegistrar, ResourceLoaderAware

集成了ImportBeanDEfinantionResigt,通过registerBeanDefianntins可以向IOC容器注入一些组件:

@Override protected boolean isCandidateComponent(AnnotatedBeanDefinition beanDefinition) { return beanDefinition.getMetadata().isInterface() && beanDefinition.getMetadata().isIndependent(); }

代码逻辑就是要把Mapper类型的接口那些类都扫描进来。然后对扫描出来的Bean定义后置处理。

至此,mybatis的自动装配完成。

# MapperRegistry#getMapper源码 public <T> T getMapper(Class<T> type, SqlSession sqlSession) { final MapperProxyFactory<T> mapperProxyFactory = (MapperProxyFactory<T>) knownMappers.get(type); if (mapperProxyFactory == null) { throw new BindingException("Type " + type + " is not known to the MapperRegistry."); } try { return mapperProxyFactory.newInstance(sqlSession); } catch (Exception e) { throw new BindingException("Error getting mapper instance. Cause: " + e, e); } }

 

在我们调用Mapper进行查询的sql查询的时候,实际上,获取的类型是上面进行后置处理的,修改的Mapping

factoryBean 类型。

而MapperFactoryBean 又是一个FactotyBean类型,在IOC进行getBean调用的getObject.

最终获取到的bean实例,实际上是一个MapperProxy类型在执行语句的时候,就会调用的

MapperProxy#invoke进行拦截,最终调用sqlSession进行语句的执行

至此,SpringBoot整合mybatis流程结束。

 

 

 

参考资料:

https://www.yuque.com/zhanyifan-rkxpe/grf7g5/lomxqd

 

 

 

 

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

执于代码

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值