阿里面试被刷经验: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的原理讲的很好 ,帮助很大