下面這句話意思非常明瞭,就是通過傳入接口類型對象,獲取接口代理對象。
IUserDao userDao1 = sqlSession1.getMapper(IUserDao.class);
具體的過程如下:
一、首先,調用SqlSession的實現類DefaultSqlSession的getMapper方法,其實是在該方法內調用configuration的getMapper方法,將接口類對象以及當前sqlsession對象傳入。
//DefaultSqlSession.java
@Override
public <T> T getMapper(Class<T> type) {
//調用configuration的getMapper
return configuration.<T>getMapper(type, this);
}
二、接着調用我們熟悉的mapperRegistry,因爲我們知道,在讀取配置文件,創建sqlSession的時候,接口類型信息就已經被存入到其內部維護的Map之中。
//Configuration.java
public <T> T getMapper(Class<T> type, SqlSession sqlSession) {
return mapperRegistry.getMapper(type, sqlSession);
}
三、我們來看看getMapper方法具體的實現如何:
public <T> T getMapper(Class<T> type, SqlSession sqlSession) {
//根據傳入的類型獲取對應的鍵,也就是這個代理工廠
final MapperProxyFactory<T> mapperProxyFactory = (MapperProxyFactory<T>) knownMappers.get(type);
if (mapperProxyFactory == null) {
throw new BindingException("Type " + type + " is not known to the MapperRegistry.");
}
try {
//最終返回的是代理工廠產生的一個實例對象
return mapperProxyFactory.newInstance(sqlSession);
} catch (Exception e) {
throw new BindingException("Error getting mapper instance. Cause: " + e, e);
}
}
四、緊接着,我們進入MapperProxyFactory,真真實實地發現了創建代理對象的過程。
protected T newInstance(MapperProxy<T> mapperProxy) {
//創建MapperProxy代理對象
return (T) Proxy.newProxyInstance(mapperInterface.getClassLoader(), new Class[] { mapperInterface }, mapperProxy);
}
public T newInstance(SqlSession sqlSession) {
//MapperProxy是代理類,
final MapperProxy<T> mapperProxy = new MapperProxy<T>(sqlSession, mapperInterface, methodCache);
return newInstance(mapperProxy);
}