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