Mybatis:整合Spring

SqlSessionFactory何时创建

容器启动时创建

能否直接使用DefaultSqlSession

不能,因为该类不是线程安全的,直接用会有问题,Spring环境中使用了SqlSessionTemplate类代替
为什么SqlSessionTemplate是线程安全的:SqlSessionTemplate中有一个sqlSessionProxy,该类是代理了DefaultSqlSession的类,内部每次都从线程内部的Threadlocal拿到sqlSession。

怎么在DAO层的实现类获得SqlSessionTemplate

继承SqlSessionDaoSupport类,就可以拿到SqlSessionTemplate。但是实际使用过程中压根没有继承SqlSessionDaoSupport类,实际中都是直接通过@Autowired注入使用了。
因为注册到容器中的是MapperFactoryBean,在注入的时候调用了MapperFactoryBean的getObject()方法,该类MapperFactoryBean继承了SqlSessionDaoSupport类,可以拿到SqlSessionTemplate,再通过SqlSessionTemplate.getMapper()方法,返回了Mapper的代理对象(和Mybatis自己返回的一样了)。

接口扫描注册

什么时候扫描,注册到容器中的是什么
BeanDefinition注册完以后的扫描,注册到容器中的是MapperFactoryBean。

原文地址:https://www.cnblogs.com/fcb-it/p/13276321.html