2020-11-02学习mybatis原理

阿里面试被刷经验:mybatis原理

分析了正在参与一个springmvc + mybatis项目,之前一直没想通到底myabtis的mapper是如何注入到spring的bean中作为dao。启动本地项目后,debug分析了一下流程

1.初始化web上下文时加载mybatis-config.xml配置:

ContextLoaderListener -> XmlWebApplicationContext -> DefaultListableBeanFactory.invokeInitMethods -> SqlSessionFactoryBean.afterPropertiesSet() -> SqlSessionFactoryBean.buildSqlSessionFactory 
(这里会根据mybatis的配置初始化mapper映射出来的代理) -> XMLMapperBuilder.parse -> XMLMapperBuilder.bindMapperForNamespace() -> Configuration.addMapper 
-> MapperRegistry.addMapper(到这一步动态代理就建立好了;每个***Mapper 都有一个 MapperProxyFactory 实力与之对应)

2.初始化springmvc的上下文时,通过工厂注册注入bean依赖的属性

ContextLoaderListener -> XmlWebApplicationContext -> FactoryBeanRegistrySupport -> MapperFactoryBean.getObject -> SqlSessionTemplate.getMapper
-> Configuration.getMapper -> MapperRegistry.getMapper -> mapperProxyFactory.newInstance(sqlSession)

package org.apache.ibatis.binding;

public class MapperProxyFactory<T> {

    //为mapperInterface(比如userMapper) new一个MapperProxy
    public T newInstance(SqlSession sqlSession) {
        final MapperProxy<T> mapperProxy = new MapperProxy<T>(sqlSession, mapperInterface, methodCache);
        return newInstance(mapperProxy);
      }
     
    //JDK动态代理 
    protected T newInstance(MapperProxy<T> mapperProxy) {
        return (T) Proxy.newProxyInstance(mapperInterface.getClassLoader(), new Class[] { mapperInterface }, mapperProxy);
      }
}

https://www.cnblogs.com/adolfmc/p/8997281.html (MyBatis框架及原理分析) 这篇文章很好,对于mybatis的原理讲的很好 ,帮助很大

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值