MyBatis插件機制超詳細(xì)講解
MyBatis的插件機制
MyBatis 允許在已映射語句執(zhí)行過程中的某一點進(jìn)行攔截調(diào)用。默認(rèn)情況下,MyBatis 允許使用插件來攔截的方法調(diào)用包括:
- Executor(update, query, flushStatements, commit, rollback, getTransaction, close, isClosed)
- ParameterHandler(getParameterObject, setParameters)
- ResultSetHandler(handleResultSets, handleOutputParameters)
- StatementHandler(prepare, parameterize, batch, update, query)
這里我們再回顧一下,在創(chuàng)建StatementHandler時,我們看到了如下代碼:
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;
}
InterceptorChain
在全局配置Configuration中維護了一個InterceptorChain interceptorChain = new InterceptorChain()攔截器鏈,其內(nèi)部維護了一個私有常量List<Interceptor> interceptors,其pluginAll方法為遍歷interceptors并調(diào)用每個攔截器的plugin方法。
public class InterceptorChain {
private final List<Interceptor> interceptors = new ArrayList<Interceptor>();
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<Interceptor> getInterceptors() {
return Collections.unmodifiableList(interceptors);
}
}MyBatis中攔截器接口
package org.apache.ibatis.plugin;
import java.util.Properties;
public interface Interceptor {
//攔截處理,也就是代理對象目標(biāo)方法執(zhí)行前被處理
Object intercept(Invocation invocation) throws Throwable;
//生成代理對象
Object plugin(Object target);
//設(shè)置屬性
void setProperties(Properties properties);
}
如果想自定義插件,那么就需要實現(xiàn)該接口。
MyBatis中的Invocation
package org.apache.ibatis.plugin;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class Invocation {
//目標(biāo)對象
private final Object target;
//目標(biāo)對象的方法
private final Method method;
//方法參數(shù)
private final 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;}
//proceed-繼續(xù),也就是說流程繼續(xù)往下執(zhí)行,這里看方法就是目標(biāo)方法反射調(diào)用。
public Object proceed() throws InvocationTargetException, IllegalAccessException {
return method.invoke(target, args);
}
}MyBatis中的Plugin
package org.apache.ibatis.plugin;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.apache.ibatis.reflection.ExceptionUtil;
public class Plugin implements InvocationHandler {
//目標(biāo)對象 ,被代理的對象
private final Object target;
//攔截器
private final Interceptor interceptor;
//方法簽名集合
private final Map<Class<?>, Set<Method>> signatureMap;
private Plugin(Object target, Interceptor interceptor, Map<Class<?>, Set<Method>> signatureMap) {
this.target = target;
this.interceptor = interceptor;
this.signatureMap = signatureMap;
}
//該方法會獲取signatureMap中包含的所有target實現(xiàn)的接口,然后生成代理對象
public static Object wrap(Object target, Interceptor interceptor) {
Map<Class<?>, Set<Method>> 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;
}
//每一個InvocationHandler 的invoke方法會在代理對象的目標(biāo)方法執(zhí)行前被觸發(fā)
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
try {
Set<Method> 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);
}
}
//獲取攔截器感興趣的接口與方法
private static Map<Class<?>, Set<Method>> getSignatureMap(Interceptor interceptor) {
Intercepts interceptsAnnotation = interceptor.getClass().getAnnotation(Intercepts.class);
// issue #251
if (interceptsAnnotation == null) {
throw new PluginException("No @Intercepts annotation was found in interceptor " + interceptor.getClass().getName());
}
Signature[] sigs = interceptsAnnotation.value();
Map<Class<?>, Set<Method>> signatureMap = new HashMap<>();
for (Signature sig : sigs) {
Set<Method> methods = signatureMap.computeIfAbsent(sig.type(), k -> new HashSet<>());
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;
}
//該方法會獲取signatureMap中包含的所有type實現(xiàn)的接口與上級接口
private static Class<?>[] getAllInterfaces(Class<?> type, Map<Class<?>, Set<Method>> signatureMap) {
Set<Class<?>> 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()]);
}
}這里Plugin實現(xiàn)了InvocationHandler,那么其invoke方法會在代理對象的目標(biāo)方法執(zhí)行前被觸發(fā)。其invoke方法解釋如下:
- ① 獲取當(dāng)前Plugin感興趣的方法類型,判斷目標(biāo)方法Method是否被包含;
- ② 如果當(dāng)前目標(biāo)方法是Plugin感興趣的,那么就
interceptor.intercept(new Invocation(target, method, args));觸發(fā)攔截器的intercept方法; - ③ 如果當(dāng)前目標(biāo)方法不是Plugin感興趣的,直接執(zhí)行目標(biāo)方法。
上面說Plugin感興趣其實是指內(nèi)部的interceptor感興趣。
MyBatis插件開發(fā)
如下所示,編寫插件實現(xiàn)Interceptor接口,并使用@Intercepts注解完成插件簽名。
package com.mybatis.dao;
import java.util.Properties;
import org.apache.ibatis.executor.parameter.ParameterHandler;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Plugin;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.SystemMetaObject;
/**
* 完成插件簽名:告訴MyBatis當(dāng)前插件用來攔截哪個對象的哪個方法
*/
@Intercepts({@Signature(type=StatementHandler.class,method="parameterize",args=java.sql.Statement.class)})
public class MyFirstPlugin implements Interceptor{
@Override
public Object intercept(Invocation invocation) throws Throwable {
// TODO Auto-generated method stub
System.out.println("MyFirstPlugin...intercept:"+invocation.getMethod());
Object target = invocation.getTarget();
System.out.println("當(dāng)前攔截到的對象:"+target);
//拿到:StatementHandler==>ParameterHandler===>parameterObject
//拿到target的元數(shù)據(jù)
MetaObject metaObject = SystemMetaObject.forObject(target);
Object value = metaObject.getValue("parameterHandler.parameterObject");
System.out.println("sql語句用的參數(shù)是:"+value);
//修改完sql語句要用的參數(shù)
metaObject.setValue("parameterHandler.parameterObject", 11);
//執(zhí)行目標(biāo)方法
Object proceed = invocation.proceed();
//返回執(zhí)行后的返回值
return proceed;
}
//plugin:包裝目標(biāo)對象的:包裝:為目標(biāo)對象創(chuàng)建一個代理對象
@Override
public Object plugin(Object target) {
//我們可以借助Plugin的wrap方法來使用當(dāng)前Interceptor包裝我們目標(biāo)對象
System.out.println("MyFirstPlugin...plugin:mybatis將要包裝的對象"+target);
Object wrap = Plugin.wrap(target, this);
//返回為當(dāng)前target創(chuàng)建的動態(tài)代理
return wrap;
}
//setProperties:將插件注冊時 的property屬性設(shè)置進(jìn)來
@Override
public void setProperties(Properties properties) {
// TODO Auto-generated method stub
System.out.println("插件配置的信息:"+properties);
}
}注冊到mybatis的全局配置文件中,示例如下(注意,插件是可以設(shè)置屬性的如這里我們可以設(shè)置用戶名、密碼):
<plugins>
<plugin interceptor="com.mybatis.dao.MyFirstPlugin">
<property name="username" value="root"/>
<property name="password" value="123456"/>
</plugin>
</plugins>
那么mybatis在執(zhí)行過程中實例化Executor、ParameterHandler、ResultSetHandler和StatementHandler時都會觸發(fā)上面我們自定義插件的plugin方法。
如果有多個插件,那么攔截器鏈包裝的時候會從前到后,執(zhí)行的時候會從后到前。如這里生成的StatementHandler代理對象如下:

總結(jié)
- 按照插件注解聲明,按照插件配置順序調(diào)用插件
plugin方法,生成被攔截對象的動態(tài)代理; - 多個插件依次生成目標(biāo)對象的代理對象,層層包裹,先聲明的先包裹,形成代理鏈;
- 目標(biāo)方法執(zhí)行時依次從外到內(nèi)執(zhí)行插件的
intercept方法。 - 多個插件情況下,我們往往需要在某個插件中分離出目標(biāo)對象??梢越柚?code>MyBatis提供的
SystemMetaObject類來進(jìn)行獲取最后一層的h以及target屬性的值
到此這篇關(guān)于MyBatis插件機制超詳細(xì)講解的文章就介紹到這了,更多相關(guān)MyBatis插件機制內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
spring-data-jpa實現(xiàn)增刪改查以及分頁操作方法
下面小編就為大家分享一篇spring-data-jpa實現(xiàn)增刪改查以及分頁操作方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-02-02
IntelliJ IDEA 創(chuàng)建 Java 項目及創(chuàng)建 Java 文件并運行的詳細(xì)步驟
這篇文章主要介紹了IntelliJ IDEA 創(chuàng)建 Java 項目及創(chuàng)建 Java 文件并運行的詳細(xì)步驟,本文通過圖文并茂的形式給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-11-11
JDBC插入數(shù)據(jù)返回數(shù)據(jù)主鍵代碼實例
這篇文章主要介紹了JDBC插入數(shù)據(jù)返回數(shù)據(jù)主鍵代碼實例,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-11-11
Mybatis框架之工廠模式(Factory Pattern)
MyBatis中使用工廠模式來管理和創(chuàng)建SqlSession對象,從而簡化數(shù)據(jù)庫訪問的配置和管理過程,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2024-11-11
使用SpringBoot+nmap4j獲取端口信息的代碼詳解
這篇文章主要介紹了使用 SpringBoot + nmap4j 獲取端口信息,包括需求背景、nmap4j 的相關(guān)介紹、代碼說明(含測試代碼、改造后的代碼及參數(shù)說明),還提到了文件讀取方式和依賴引入方式,最終請求能獲取到數(shù)據(jù),需要的朋友可以參考下2025-01-01
Java數(shù)據(jù)結(jié)構(gòu)(線性表)詳解
本文主要介紹了Java數(shù)據(jù)結(jié)構(gòu)(線性表)的相關(guān)知識。具有很好的參考價值,下面跟著小編一起來看下吧2017-01-01
springboot?@Validated的概念及示例實戰(zhàn)
這篇文章主要介紹了springboot?@Validated的概念以及實戰(zhàn),使用?@Validated?注解,Spring?Boot?應(yīng)用可以有效地實現(xiàn)輸入驗證,提高數(shù)據(jù)的準(zhǔn)確性和應(yīng)用的安全性,本文結(jié)合實例給大家講解的非常詳細(xì),需要的朋友可以參考下2024-04-04
SpringBoot項目打包war包時無法運行問題的解決方式
在開發(fā)工程中,使用啟動類啟動能夠正常啟動并測試,下面這篇文章主要給大家介紹了關(guān)于SpringBoot項目打包war包時無法運行問題的解決方式,文中通過實例代碼介紹的非常詳細(xì),需要的朋友可以參考下2022-06-06

