欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

MyBatis插件機制超詳細講解

 更新時間:2022年11月01日 15:13:26   作者:流煙默  
MyBatis在四大對象的創(chuàng)建過程中,都會有插件進行介入。插件可以利用動態(tài)代理機制一層層的包裝目標(biāo)對象,而實現(xiàn)在目標(biāo)對象執(zhí)行目標(biāo)方法之前進行攔截的效果

MyBatis的插件機制

MyBatis 允許在已映射語句執(zhí)行過程中的某一點進行攔截調(diào)用。默認情況下,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è)置進來
	@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)對象。可以借助MyBatis提供的SystemMetaObject類來進行獲取最后一層的h以及target屬性的值

到此這篇關(guān)于MyBatis插件機制超詳細講解的文章就介紹到這了,更多相關(guān)MyBatis插件機制內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • Json轉(zhuǎn)化為Java對象的實例詳解

    Json轉(zhuǎn)化為Java對象的實例詳解

    這篇文章主要介紹了Json轉(zhuǎn)化為Java對象的實例詳解的相關(guān)資料,前后端數(shù)據(jù)交互的情況經(jīng)常會遇到Json串與java 對象的相互轉(zhuǎn)換方便操作,需要的朋友可以參考下
    2017-08-08
  • Java基礎(chǔ)夯實之線程問題全面解析

    Java基礎(chǔ)夯實之線程問題全面解析

    操作系統(tǒng)支持多個應(yīng)用程序并發(fā)執(zhí)行,每個應(yīng)用程序至少對應(yīng)一個進程?。進程是資源分配的最小單位,而線程是CPU調(diào)度的最小單位。本文將帶大家全面解析線程相關(guān)問題,感興趣的可以了解一下
    2022-11-11
  • MyBatisPlus代碼生成器的原理及實現(xiàn)詳解

    MyBatisPlus代碼生成器的原理及實現(xiàn)詳解

    這篇文章主要為大家詳細介紹了MyBatisPlus中代碼生成器的原理及實現(xiàn),文中的示例代碼講解詳細,對我們學(xué)習(xí)MyBatisPlus有一定幫助,需要的可以參考一下
    2022-08-08
  • SpringBoot配置數(shù)據(jù)庫密碼加密的實現(xiàn)

    SpringBoot配置數(shù)據(jù)庫密碼加密的實現(xiàn)

    這篇文章主要介紹了SpringBoot配置數(shù)據(jù)庫密碼加密的實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2021-03-03
  • java中幾種http請求方式示例詳解

    java中幾種http請求方式示例詳解

    在日常工作和學(xué)習(xí)中有很多地方都需要發(fā)送HTTP請求,下面這篇文章主要給大家介紹了關(guān)于java中幾種http請求方式的相關(guān)資料,文中通過代碼介紹的非常詳細,需要的朋友可以參考下
    2023-11-11
  • idea中的jvm調(diào)優(yōu)方式

    idea中的jvm調(diào)優(yōu)方式

    這篇文章主要介紹了idea中的jvm調(diào)優(yōu)方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2023-12-12
  • web中拖拽排序和java后臺交互實現(xiàn)方法示例

    web中拖拽排序和java后臺交互實現(xiàn)方法示例

    這篇文章主要給大家介紹了關(guān)于web中拖拽排序和java后臺交互實現(xiàn)的相關(guān)資料,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2018-12-12
  • 詳解Java 對象序列化和反序列化

    詳解Java 對象序列化和反序列化

    本篇文章主要介紹了Java 對象序列化和反序列化,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2017-03-03
  • Java設(shè)計模式之抽象工廠模式簡析

    Java設(shè)計模式之抽象工廠模式簡析

    這篇文章主要介紹了Java設(shè)計模式之抽象工廠模式簡析, 抽象工廠模式是工廠方法模式的升級版本,他用來創(chuàng)建一組相關(guān)或者相互依賴的對象,他與工廠方法模式的區(qū)別就在于,工廠方法模式針對的是一個產(chǎn)品等級結(jié)構(gòu),需要的朋友可以參考下
    2023-12-12
  • 深入理解java動態(tài)代理機制

    深入理解java動態(tài)代理機制

    本篇文章主要介紹了深入理解java動態(tài)代理機制,詳細的介紹動態(tài)代理有哪些應(yīng)用場景,什么是動態(tài)代理,怎樣使用,它的局限性在什么地方?有興趣的可以了解一下。
    2017-02-02

最新評論