Mybatis源码:getMapper获取接口代理对象

测试代码:

    @Test
    public void test01() throws IOException {
        //1.根据xml配置文件(全局配置文件)创建一个SqlSessionFactory对象
        SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
        SqlSession session = sqlSessionFactory.openSession();
        try {
            EmployeeMapper employeeMapper= session.getMapper(EmployeeMapper.class);
            Employee emp = employeeMapper.getEmpById(1);
            System.out.println(emp);

            session.clearCache();

            Employee emp2 = employeeMapper.getEmpById(2);
            System.out.println(emp2);
            System.out.println(emp==emp2);
        } finally {
            session.close();
        }
    }

    private SqlSessionFactory getSqlSessionFactory() throws IOException {
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        return new SqlSessionFactoryBuilder().build(inputStream);
    }

在getMapper处打上断点,并进入方法,调用的是DefualtSqlSession的getMapper方法,最终调用的是Configuration的getMapper方法

image-20210114112438460

configuration调用的是mapperRegistry的getMapper方法

public <T> T getMapper(Class<T> type, SqlSession sqlSession) {
  return mapperRegistry.getMapper(type, sqlSession);
}

image-20210114112701531

mapperRegistry的getMapper方法,先去获取mapperProxyFactory(mapper代理类的创建工厂),然后通过mapperProxyFactory的newInstance方法创建出对应的代理对象,点击进入

image-20210114121745624

发现MapperProxyFactory通过jdk动态代理创建了mapper接口的代理类MapperProxy。

而MapperProxy实现了InvocationHandler接口

image-20210114122134087

所以最终getMapper返回的是一个代理对象

image-20210114122344249

原文地址:https://www.cnblogs.com/wwjj4811/p/14276547.html