MyBatis提供了一種插件(plugin)的功能,雖然叫作插件,但其實這是攔截器功能。那麼攔截器攔截MyBatis中的哪些內容呢?sql
咱們進入官網看一看:數組
MyBatis攔截器介紹架構
MyBatis提供了一種插件(plugin)的功能,雖然叫作插件,但其實這是攔截器功能。那麼攔截器攔截MyBatis中的哪些內容呢?併發
咱們進入官網看一看:app
MyBatis 容許你在已映射語句執行過程當中的某一點進行攔截調用。默認狀況下,MyBatis 容許使用插件來攔截的方法調用包括:Executor (update, query, flushStatements, commit, rollback, getTransaction, close, isClosed)ParameterHandler (getParameterObject, setParameters)ResultSetHandler (handleResultSets, handleOutputParameters)StatementHandler (prepare, parameterize, batch, update, query)分佈式
咱們看到了能夠攔截Executor接口的部分方法,好比update,query,commit,rollback等方法,還有其餘接口的一些方法等。ide
整體歸納爲:函數
攔截執行器的方法高併發
攔截參數的處理源碼分析
攔截結果集的處理
攔截Sql語法構建的處理
攔截器的使用
攔截器介紹及配置
首先咱們看下MyBatis攔截器的接口定義:
public interface Interceptor {
Object intercept(Invocation invocation) throws Throwable;
Object plugin(Object target);
void setProperties(Properties properties);
}
比較簡單,只有3個方法。 MyBatis默認沒有一個攔截器接口的實現類,開發者們能夠實現符合本身需求的攔截器。
下面的MyBatis官網的一個攔截器實例:
@Intercepts({@Signature(
type= Executor.class,
method = "update",
args = {MappedStatement.class,Object.class})})
public class ExamplePlugin implements Interceptor {
public Object intercept(Invocation invocation) throws Throwable {
return invocation.proceed();
}
public Object plugin(Object target) {
return Plugin.wrap(target, this);
}
public void setProperties(Properties properties) {
}
}
全局xml配置:
這個攔截器攔截Executor接口的update方法(其實也就是SqlSession的新增,刪除,修改操做),全部執行executor的update方法都會被該攔截器攔截到。
源碼分析
下面咱們分析一下這段代碼背後的源碼。
首先從源頭->配置文件開始分析:
XMLConfigBuilder解析MyBatis全局配置文件的pluginElement私有方法:
private void pluginElement(XNode parent) throws Exception {
if (parent != null) {
for (XNode child : parent.getChildren()) {
String interceptor = child.getStringAttribute("interceptor");
Properties properties = child.getChildrenAsProperties();
Interceptor interceptorInstance = (Interceptor) resolveClass(interceptor).newInstance();
interceptorInstance.setProperties(properties);
configuration.addInterceptor(interceptorInstance);
}
}
}
具體的解析代碼其實比較簡單,就不貼了,主要就是經過反射實例化plugin節點中的interceptor屬性表示的類。而後調用全局配置類Configuration的addInterceptor方法。
public void addInterceptor(Interceptor interceptor) {
interceptorChain.addInterceptor(interceptor);
}
這個interceptorChain是Configuration的內部屬性,類型爲InterceptorChain,也就是一個攔截器鏈,咱們來看下它的定義:
public class InterceptorChain {
private final List interceptors = new ArrayList();
public Object pluginAll(Object target) {
for (Interceptor interceptor : interceptors) {
target = interceptor.plugin(target);
}
return target;
}
public void addInterceptor(Interceptor interceptor) {
interceptors.add(interceptor);
}
public List getInterceptors() {
return Collections.unmodifiableList(interceptors);
}
}
如今咱們理解了攔截器配置的解析以及攔截器的歸屬,如今咱們回過頭看下爲什麼攔截器會攔截這些方法(Executor,ParameterHandler,ResultSetHandler,StatementHandler的部分方法):
public ParameterHandler newParameterHandler(MappedStatement mappedStatement, Object parameterObject, BoundSql boundSql) {
ParameterHandler parameterHandler = mappedStatement.getLang().createParameterHandler(mappedStatement, parameterObject, boundSql);
parameterHandler = (ParameterHandler) interceptorChain.pluginAll(parameterHandler);
return parameterHandler;
}
public ResultSetHandler newResultSetHandler(Executor executor, MappedStatement mappedStatement, RowBounds rowBounds, ParameterHandler parameterHandler,
ResultHandler resultHandler, BoundSql boundSql) {
ResultSetHandler resultSetHandler = new DefaultResultSetHandler(executor, mappedStatement, parameterHandler, resultHandler, boundSql, rowBounds);
resultSetHandler = (ResultSetHandler) interceptorChain.pluginAll(resultSetHandler);
return resultSetHandler;
}
public StatementHandler newStatementHandler(Executor executor, MappedStatement mappedStatement, Object parameterObject, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) {
StatementHandler statementHandler = new RoutingStatementHandler(executor, mappedStatement, parameterObject, rowBounds, resultHandler, boundSql);
statementHandler = (StatementHandler) interceptorChain.pluginAll(statementHandler);
return statementHandler;
}
public Executor newExecutor(Transaction transaction, ExecutorType executorType, boolean autoCommit) {
executorType = executorType == null ? defaultExecutorType : executorType;
executorType = executorType == null ? ExecutorType.SIMPLE : executorType;
Executor executor;
if (ExecutorType.BATCH == executorType) {
executor = new BatchExecutor(this, transaction);
} else if (ExecutorType.REUSE == executorType) {
executor = new ReuseExecutor(this, transaction);
} else {
executor = new SimpleExecutor(this, transaction);
}
if (cacheEnabled) {
executor = new CachingExecutor(executor, autoCommit);
}
executor = (Executor) interceptorChain.pluginAll(executor);
return executor;
}
以上4個方法都是Configuration的方法。這些方法在MyBatis的一個操做(新增,刪除,修改,查詢)中都會被執行到,執行的前後順序是Executor,ParameterHandler,ResultSetHandler,StatementHandler(其中ParameterHandler和ResultSetHandler的建立是在建立StatementHandler[3個可用的實現類CallableStatementHandler,PreparedStatementHandler,SimpleStatementHandler]的時候,其構造函數調用的[這3個實現類的構造函數其實都調用了父類BaseStatementHandler的構造函數])。
這4個方法實例化了對應的對象以後,都會調用interceptorChain的pluginAll方法,InterceptorChain的pluginAll剛纔已經介紹過了,就是遍歷全部的攔截器,而後調用各個攔截器的plugin方法。注意:攔截器的plugin方法的返回值會直接被賦值給原先的對象
因爲能夠攔截StatementHandler,這個接口主要處理sql語法的構建,所以好比分頁的功能,能夠用攔截器實現,只須要在攔截器的plugin方法中處理StatementHandler接口實現類中的sql便可,可以使用反射實現。
MyBatis還提供了 @Intercepts和 @Signature關於攔截器的註解。官網的例子就是使用了這2個註解,還包括了Plugin類的使用:
public Object plugin(Object target) {
return Plugin.wrap(target, this);
}
下面咱們就分析這3個 "新組合" 的源碼,首先先看Plugin類的wrap方法:
public static Object wrap(Object target, Interceptor interceptor) {
Map, Set> signatureMap = getSignatureMap(interceptor);
Class type = target.getClass();
Class[] interfaces = getAllInterfaces(type, signatureMap);
if (interfaces.length > 0) {
return Proxy.newProxyInstance(
type.getClassLoader(),
interfaces,
new Plugin(target, interceptor, signatureMap));
}
return target;
}
Plugin類實現了InvocationHandler接口,很明顯,咱們看到這裏返回了一個JDK自身提供的動態代理類。咱們解剖一下這個方法調用的其餘方法:
getSignatureMap方法:
private static Map, Set> getSignatureMap(Interceptor interceptor) {
Intercepts interceptsAnnotation = interceptor.getClass().getAnnotation(Intercepts.class);
if (interceptsAnnotation == null) { // issue #251
throw new PluginException("No @Intercepts annotation was found in interceptor " + interceptor.getClass().getName());
}
Signature[] sigs = interceptsAnnotation.value();
Map, Set> signatureMap = new HashMap, Set>();
for (Signature sig : sigs) {
Set methods = signatureMap.get(sig.type());
if (methods == null) {
methods = new HashSet();
signatureMap.put(sig.type(), methods);
}
try {
Method method = sig.type().getMethod(sig.method(), sig.args());
methods.add(method);
} catch (NoSuchMethodException e) {
throw new PluginException("Could not find method on " + sig.type() + " named " + sig.method() + ". Cause: " + e, e);
}
}
return signatureMap;
}
getSignatureMap方法解釋:首先會拿到攔截器這個類的 @Interceptors註解,而後拿到這個註解的屬性 @Signature註解集合,而後遍歷這個集合,遍歷的時候拿出 @Signature註解的type屬性(Class類型),而後根據這個type獲得帶有method屬性和args屬性的Method。因爲 @Interceptors註解的 @Signature屬性是一個屬性,因此最終會返回一個以type爲key,value爲Set的Map。
@Intercepts({@Signature(
type= Executor.class,
method = "update",
args = {MappedStatement.class,Object.class})})
好比這個 @Interceptors註解會返回一個key爲Executor,value爲集合(這個集合只有一個元素,也就是Method實例,這個Method實例就是Executor接口的update方法,且這個方法帶有MappedStatement和Object類型的參數)。這個Method實例是根據 @Signature的method和args屬性獲得的。若是args參數跟type類型的method方法對應不上,那麼將會拋出異常。
getAllInterfaces方法:
private static Class[] getAllInterfaces(Class type, Map, Set> signatureMap) {
Set> interfaces = new HashSet>();
while (type != null) {
for (Class c : type.getInterfaces()) {
if (signatureMap.containsKey(c)) {
interfaces.add(c);
}
}
type = type.getSuperclass();
}
return interfaces.toArray(new Class[interfaces.size()]);
}
getAllInterfaces方法解釋:根據目標實例target(這個target就是以前所說的MyBatis攔截器能夠攔截的類,Executor,ParameterHandler,ResultSetHandler,StatementHandler)和它的父類們,返回signatureMap中含有target實現的接口數組。
因此Plugin這個類的做用就是根據 @Interceptors註解,獲得這個註解的屬性 @Signature數組,而後根據每一個 @Signature註解的type,method,args屬性使用反射找到對應的Method。最終根據調用的target對象實現的接口決定是否返回一個代理對象替代原先的target對象。
好比MyBatis官網的例子,當Configuration調用newExecutor方法的時候,因爲Executor接口的update(MappedStatement ms, Object parameter)方法被攔截器被截獲。所以最終返回的是一個代理類Plugin,而不是Executor。這樣調用方法的時候,若是是個代理類,那麼會執行:
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
try {
Set methods = signatureMap.get(method.getDeclaringClass());
if (methods != null && methods.contains(method)) {
return interceptor.intercept(new Invocation(target, method, args));
}
return method.invoke(target, args);
} catch (Exception e) {
throw ExceptionUtil.unwrapThrowable(e);
}
}
沒錯,若是找到對應的方法被代理以後,那麼會執行Interceptor接口的interceptor方法。
這個Invocation類以下:
public class Invocation {
private Object target;
private Method method;
private Object[] args;
public Invocation(Object target, Method method, Object[] args) {
this.target = target;
this.method = method;
this.args = args;
}
public Object getTarget() {
return target;
}
public Method getMethod() {
return method;
}
public Object[] getArgs() {
return args;
}
public Object proceed() throws InvocationTargetException, IllegalAccessException {
return method.invoke(target, args);
}
}
它的proceed方法也就是調用原先方法(不走代理)。
總結
MyBatis攔截器接口提供的3個方法中,plugin方法用於某些處理器(Handler)的構建過程。interceptor方法用於處理代理類的執行。setProperties方法用於攔截器屬性的設置。
其實MyBatis官網提供的使用 @Interceptors和 @Signature註解以及Plugin類這樣處理攔截器的方法,咱們不必定要直接這樣使用。咱們也能夠拋棄這3個類,直接在plugin方法內部根據target實例的類型作相應的操做。
整體來講MyBatis攔截器仍是很簡單的,攔截器自己不須要太多的知識點,可是學習攔截器須要對MyBatis中的各個接口很熟悉,由於攔截器涉及到了各個接口的知識點。
歡迎工做一到五年想成爲Java工程師的朋友們加入Java架構開發:744677563
羣內提供免費的Java架構學習資料(裏面有高可用、高併發、高性能及分佈式、Jvm性能調優、Spring源碼,MyBatis,Netty,Redis,Kafka,Mysql,Zookeeper,Tomcat,Docker,Dubbo,Nginx等多個知識點的架構資料)合理利用本身每一分每一秒的時間來學習提高本身,不要再用"沒有時間「來掩飾本身思想上的懶惰!趁年輕,使勁拼,給將來的本身一個交代!