上篇文章,解析了SqlSession 的创建过程,本章延续上章的内容,接着SqlSession 来讲解MapperProxy。

1、通过sqlSession 调用getMapper() 方法,来解析过程。

MyBatis源码解读(2)——MapperProxy

接着上一篇讲到通过 DefaultSqlSessionFactory 可以得到一个 SqlSession 的实例 DefaultSqlSession 。

MyBatis源码解读(2)——MapperProxy

通过 DefaultSqlSession 中的 getMapper() 方法来得到mapper 。

MyBatis源码解读(2)——MapperProxy

MyBatis源码解读(2)——MapperProxy

UserMapper仅仅是一个接口,这里会涉及到Java的动态代理。通过打断点调试我们可以发现确实产生了一个叫MapperProxy的代理类。

MyBatis源码解读(2)——MapperProxy

在getMapper()的方法中调用的是 Configuration 的 getMapper() 方法。那为什么会产生 MapperProxy代理类呢?

下面来解析 MapperProxy 类的产生过程?接着上面继续分析。

1.、点击getMapper() 方法 ,进入到 Configuration 类的getMapper() 方法。

MyBatis源码解读(2)——MapperProxy

2、接着进入到了接口注册类 MapperRegistry 中的getMapper() 中,在方法中创建了mapperProxyFactory 代理工厂。

MyBatis源码解读(2)——MapperProxy

3、点击 mapperProxyFactory 的 newInstance(sqlSession) 方法,进入到 MapperProxyFactory 代理工厂类。

   发现在 newInstance() 方法中创建了 MapperProxy 的代理对象。

MyBatis源码解读(2)——MapperProxy

到此 MapperProxy 的产生过程就结束了。

总结: Configuration.getMapper() --》MapperRegistrygetMapper() --》mapperProxyFactory.newInstance()  --》MapperProxy

 

在 MapperProxy 的解析过程中,本人产生了一个疑问Mapper 接口是在什么时候注入到了MapperProxyFactory 中。

1、通过代码发现在 SqlSessionFactory 的build() 方法中有配置文件的解析方法。

MyBatis源码解读(2)——MapperProxy

2、在 XMLConfigBuilder 类的 mapperElement() 方法中把接口对象注入到了 configuration 类中。

MyBatis源码解读(2)——MapperProxy

3、接着在 Configuration 类中把接口对象添加到了 MapperRegistry 类中。

MyBatis源码解读(2)——MapperProxy

MyBatis源码解读(2)——MapperProxy

4、在 MapperRegistry 类的addMapper 方法中将 mapper接口注入到 MapperProxyFactory 代理工厂类中。

MyBatis源码解读(2)——MapperProxy

到此mapper接口在什么时候,在什么地方注入到 MapperProxyFactory 类的过程,已经讲完了。

 

 

相关文章: