对啊,为何不须要啊?
猜猜,多是动态代理生成了接口的对应的类
果真是动态生成的java
那就是我经过class
获取Mapper
时生成的git
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
经过上面咱们一层层进入到下面的代码github
public <T> T getMapper(Class<T> type, SqlSession sqlSession) { final MapperProxyFactory<T> mapperProxyFactory = (MapperProxyFactory<T>) knownMappers.get(type);// 1 if (mapperProxyFactory == null) { throw new BindingException("Type " + type + " is not known to the MapperRegistry."); } try { return mapperProxyFactory.newInstance(sqlSession); // 2 } catch (Exception e) { throw new BindingException("Error getting mapper instance. Cause: " + e, e); } }
public T newInstance(SqlSession sqlSession) { final MapperProxy<T> mapperProxy = new MapperProxy<>(sqlSession, mapperInterface, methodCache); return newInstance(mapperProxy); // 1 }
protected T newInstance(MapperProxy<T> mapperProxy) { return (T) Proxy.newProxyInstance(mapperInterface.getClassLoader(), new Class[] { mapperInterface }, mapperProxy); }
在这里咱们又到了Proxy.newProxyInstance
代码,就是JDK建立代理的方法。面试
别着急我尚未说完呢knownMappers.get(type)
刚才咱们经过这个获取的MapperProxyFactory<T>
,其中包含生成代理的接口集合mapperInterface
如今我说说,MapperProxyFactory
从何而来,简单说就是在解析XML时建立的SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
咱们一直进入到parseConfiguration方法,其中mapperElement(root.evalNode("mappers"));
方法就是解析Mapper文件,注册的MapperProxyFactory
到MapperRegistry
。一直跟踪到下面的方法,在MapperRegistry
中。sql
public <T> void addMapper(Class<T> type) { if (type.isInterface()) { if (hasMapper(type)) { throw new BindingException("Type " + type + " is already known to the MapperRegistry."); } boolean loadCompleted = false; try { knownMappers.put(type, new MapperProxyFactory<>(type)); // 1 MapperAnnotationBuilder parser = new MapperAnnotationBuilder(config, type); parser.parse(); loadCompleted = true; } finally { if (!loadCompleted) { knownMappers.remove(type); } } }
knownMappers.put(type, new MapperProxyFactory<>(type));
方法咱们找到了,在建立代理的时候,是用的是get
方法,MapperProxyFactory
就是从这添加的。今天咱们从为Mapper接口建立代理对象开发,说到具体怎么建立对象。mybatis
从初始化配置文件,建立MapperProxyFactory<T>,到当获取Mapper,根据类型或者对应的MapperProxyFactory,使用JDK动态代理API建立代理对象。因而咱们就能够调用法了。app
演示相关代码源码分析
欢迎讨论学习学习