MyBatis原始碼解析(二)——動態代理實現函式呼叫
MyBatis在初始化的時候會將對映檔案與DAO介面一一對應,並根據對映檔案的內容為每個函式建立相應的資料庫操作能力。而我們作為MyBatis使用者,只需將DAO介面注入給Service層使用即可。 那麼MyBatis是如何根據對映檔案為每個DAO介面建立具體實現的?答案是——動態代理。 下面進入正題。
首先來回顧一項MyBatis在初始化過程中所做的事情。
MyBatis在初始化過程中,首先會讀取我們的配置檔案流程,並使用XMLConfigBuilder
來解析配置檔案。XMLConfigBuilder
會依次解析配置檔案中的各個子節點,如:<settings>
、<typeAliases>
、<mappers>
等。這些子節點在解析完成後都會被註冊進configuration
物件。然後configuration
物件將作為引數,建立SqlSessionFactory
物件。至此,初始化過程完畢!
下面我們重點分析<mapper>
節點解析的過程。
PS:MyBatis詳細的初始化過程請移步至:
節點解析過程
XMLMapperBuilder mapperParser = new XMLMapperBuilder(inputStream, configuration, resource, configuration.getSqlFragments());
mapperParser.parse();
由上述程式碼可知,解析mapper節點的解析是由XMLMapperBuilder
類的parse()
函式來完成的,下面我們就詳細看一下parse()
函式。
public void parse() { // 若當前Mapper.xml尚未載入,則載入 if (!configuration.isResourceLoaded(resource)) { // 解析<mapper>節點 configurationElement(parser.evalNode("/mapper")); // 將當前Mapper.xml標註為『已載入』(下回就不用再載入了) configuration.addLoadedResource(resource); // 【關鍵】將Mapper Class新增至Configuration中 bindMapperForNamespace(); } parsePendingResultMaps(); parsePendingCacheRefs(); parsePendingStatements(); }
這個函式主要做了兩件事:
1. 解析<mapper>
節點,並將解析結果註冊進configuration
中;
2. 將當前對映檔案所對應的DAO介面的Class物件註冊進configuration
中
這一步極為關鍵!是為了給DAO介面建立代理物件,下文會詳細介紹。
下面再進入bindMapperForNamespace()
函式,看一看它做了什麼:
private void bindMapperForNamespace() {
// 獲取當前對映檔案對應的DAO介面的全限定名
String namespace = builderAssistant.getCurrentNamespace();
if (namespace != null) {
// 將全限定名解析成Class物件
Class<?> boundType = null;
try {
boundType = Resources.classForName(namespace);
} catch (ClassNotFoundException e) {
}
if (boundType != null) {
if (!configuration.hasMapper(boundType)) {
// 將當前Mapper.xml標註為『已載入』(下回就不用再載入了)
configuration.addLoadedResource("namespace:" + namespace);
// 將DAO介面的Class物件註冊進configuration中
configuration.addMapper(boundType);
}
}
}
}
這個函式主要做了兩件事:
1. 將<mapper>
節點上定義的namespace
屬性(即:當前對映檔案所對應的DAO介面的許可權定名)解析成Class物件
2. 將該Class物件儲存在configuration
物件的MapperRegistry
容器中。
可以看一下MapperRegistry
:
public class MapperRegistry {
private final Configuration config;
private final Map<Class<?>, MapperProxyFactory<?>> knownMappers = new HashMap<Class<?>, MapperProxyFactory<?>>();
}
MapperRegistry
有且僅有兩個屬性:Configuration
和knownMappers
。
其中,knownMappers
的型別為Map<Class<?>, MapperProxyFactory<?>>
,由此可見,它是一個Map,key為DAO介面的Class物件,而Value為該DAO介面代理物件的工廠。
那麼,這個代理物件工廠是何許人也?它又是如何產生的呢?我們先來看一下MapperRegistry
的addMapper()
函式。
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 {
// 建立MapperProxyFactory物件,並put進knownMappers中
knownMappers.put(type, new MapperProxyFactory<T>(type));
MapperAnnotationBuilder parser = new MapperAnnotationBuilder(config, type);
parser.parse();
loadCompleted = true;
} finally {
if (!loadCompleted) {
knownMappers.remove(type);
}
}
}
}
從這個函式可知,MapperProxyFactory
是在這裡建立,並put進knownMappers
中的。
下面我們就來看一下MapperProxyFactory
這個類究竟有些啥:
public class MapperProxyFactory<T> {
private final Class<T> mapperInterface;
private final Map<Method, MapperMethod> methodCache = new ConcurrentHashMap<Method, MapperMethod>();
public MapperProxyFactory(Class<T> mapperInterface) {
this.mapperInterface = mapperInterface;
}
public Class<T> getMapperInterface() {
return mapperInterface;
}
public Map<Method, MapperMethod> getMethodCache() {
return methodCache;
}
@SuppressWarnings("unchecked")
protected T newInstance(MapperProxy<T> mapperProxy) {
return (T) Proxy.newProxyInstance(mapperInterface.getClassLoader(), new Class[] { mapperInterface }, mapperProxy);
}
public T newInstance(SqlSession sqlSession) {
final MapperProxy<T> mapperProxy = new MapperProxy<T>(sqlSession, mapperInterface, methodCache);
return newInstance(mapperProxy);
}
}
這個類有三個重要成員:
1. mapperInterface屬性
這個屬性就是DAO介面的Class物件,當建立MapperProxyFactory
物件的時候需要傳入
2. methodCache屬性
這個屬性用於儲存當前DAO介面中所有的方法。
3. newInstance函式
這個函式用於建立DAO介面的代理物件,它需要傳入一個MapperProxy物件作為引數。而MapperProxy類實現了InvocationHandler介面,由此可知它是動態代理中的處理類,所有對目標函式的呼叫請求都會先被這個處理類截獲,所以可以在這個處理類中新增目標函式呼叫前、呼叫後的邏輯。
DAO函式呼叫過程
當MyBatis初始化完畢後,configuration
物件中儲存了所有DAO介面的Class物件和相應的MapperProxyFactory
物件(用於建立DAO介面的代理物件)。接下來,就到了使用DAO介面中函式的階段了。
SqlSession sqlSession = sqlSessionFactory.openSession();
try {
ProductMapper productMapper = sqlSession.getMapper(ProductMapper.class);
List<Product> productList = productMapper.selectProductList();
for (Product product : productList) {
System.out.printf(product.toString());
}
} finally {
sqlSession.close();
}
我們首先需要從sqlSessionFactory
物件中建立一個SqlSession
物件,然後呼叫sqlSession.getMapper(ProductMapper.class)
來獲取代理物件。
我們先來看一下sqlSession.getMapper()
是如何建立代理物件的?
public <T> T getMapper(Class<T> type) {
return configuration.<T>getMapper(type, this);
}
sqlSession.getMapper()
呼叫了configuration.getMapper()
,那我們再看一下configuration.getMapper()
:
public <T> T getMapper(Class<T> type, SqlSession sqlSession) {
return mapperRegistry.getMapper(type, sqlSession);
}
configuration.getMapper()
又呼叫了mapperRegistry.getMapper()
,那好,我們再深入看一下mapperRegistry.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);
}
}
看到這裡我們就恍然大悟了,原來它根據上游傳遞進來DAO介面的Class物件,從configuration
中取出了該DAO介面對應的代理物件生成工廠:MapperProxyFactory
;
在有了這個工廠後,再通過newInstance
函式建立該DAO介面的代理物件,並返回給上游。
OK,此時我們已經獲取了代理物件,接下來就可以使用這個代理物件呼叫相應的函數了。
SqlSession sqlSession = sqlSessionFactory.openSession();
try {
ProductMapper productMapper = sqlSession.getMapper(ProductMapper.class);
List<Product> productList = productMapper.selectProductList();
for (Product product : productList) {
System.out.printf(product.toString());
}
} finally {
sqlSession.close();
}
以上述程式碼為例,當我們獲取到ProductMapper
的代理物件後,我們呼叫了它的selectProductList()
函式。
下面我們就來分析下代理函式呼叫過程。
當呼叫了代理物件的某一個代理函式後,這個呼叫請求首先會被髮送給代理物件處理類MapperProxy
的invoke()
函式:
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
try {
if (Object.class.equals(method.getDeclaringClass())) {
return method.invoke(this, args);
} else if (isDefaultMethod(method)) {
return invokeDefaultMethod(proxy, method, args);
}
} catch (Throwable t) {
throw ExceptionUtil.unwrapThrowable(t);
}
// 【核心代理在這裡】
final MapperMethod mapperMethod = cachedMapperMethod(method);
return mapperMethod.execute(sqlSession, args);
}
先來解釋下invoke函式的幾個引數:
1. Object proxy
:代理物件
2. Method method
:當前正在被呼叫的代理物件的函式物件
3. Object[] args
:呼叫函式的所有入參
然後,直接看invoke函式最核心的兩行程式碼:
1. cachedMapperMethod(method)
:從當前代理物件處理類MapperProxy
的methodCache
屬性中獲取method方法的詳細資訊(即:MapperMethod
物件)。如果methodCache
中沒有就建立並加進去。
2. 有了MapperMethod
物件後執行它的execute()
方法,該方法就會呼叫JDBC執行相應的SQL語句,並將結果返回給上游呼叫者。至此,代理物件函式的呼叫過程結束!
那麼execute()
函式究竟做了什麼?它是如何執行SQL語句的?
預知後事如何,且聽下回分解。