亲宝软件园·资讯

展开

MyBatis插件机制超详细讲解

流烟默 人气:0

MyBatis的插件机制

MyBatis 允许在已映射语句执行过程中的某一点进行拦截调用。默认情况下,MyBatis 允许使用插件来拦截的方法调用包括:

这里我们再回顾一下,在创建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()拦截器链,其内部维护了一个私有常量List<Interceptor> interceptors,其pluginAll方法为遍历interceptors并调用每个拦截器的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 {
  //拦截处理,也就是代理对象目标方法执行前被处理	
  Object intercept(Invocation invocation) throws Throwable;
  //生成代理对象
  Object plugin(Object target);
  //设置属性
  void setProperties(Properties properties);
}

如果想自定义插件,那么就需要实现该接口。

MyBatis中的Invocation

package org.apache.ibatis.plugin;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class Invocation {
 //目标对象
 private final Object target;
 //目标对象的方法
 private final Method method;
 //方法参数
 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-继续,也就是说流程继续往下执行,这里看方法就是目标方法反射调用。
 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 {
  //目标对象 ,被代理的对象
  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实现的接口,然后生成代理对象
  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方法会在代理对象的目标方法执行前被触发
  @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实现的接口与上级接口
  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实现了InvocationHandler,那么其invoke方法会在代理对象的目标方法执行前被触发。其invoke方法解释如下:

上面说Plugin感兴趣其实是指内部的interceptor感兴趣。

MyBatis插件开发

如下所示,编写插件实现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当前插件用来拦截哪个对象的哪个方法
 */
@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("当前拦截到的对象:"+target);
		//拿到:StatementHandler==>ParameterHandler===>parameterObject
		//拿到target的元数据
		MetaObject metaObject = SystemMetaObject.forObject(target);
		Object value = metaObject.getValue("parameterHandler.parameterObject");
		System.out.println("sql语句用的参数是:"+value);
		//修改完sql语句要用的参数
		metaObject.setValue("parameterHandler.parameterObject", 11);
		//执行目标方法
		Object proceed = invocation.proceed();
		//返回执行后的返回值
		return proceed;
	}
	 //plugin:包装目标对象的:包装:为目标对象创建一个代理对象
	@Override
	public Object plugin(Object target) {
		//我们可以借助Plugin的wrap方法来使用当前Interceptor包装我们目标对象
		System.out.println("MyFirstPlugin...plugin:mybatis将要包装的对象"+target);
		Object wrap = Plugin.wrap(target, this);
		//返回为当前target创建的动态代理
		return wrap;
	}
	 //setProperties:将插件注册时 的property属性设置进来
	@Override
	public void setProperties(Properties properties) {
		// TODO Auto-generated method stub
		System.out.println("插件配置的信息:"+properties);
	}
}

注册到mybatis的全局配置文件中,示例如下(注意,插件是可以设置属性的如这里我们可以设置用户名、密码):

<plugins>
    <plugin interceptor="com.mybatis.dao.MyFirstPlugin">
        <property name="username" value="root"/>
        <property name="password" value="123456"/>
    </plugin>
</plugins>

那么mybatis在执行过程中实例化Executor、ParameterHandler、ResultSetHandler和StatementHandler时都会触发上面我们自定义插件的plugin方法。

如果有多个插件,那么拦截器链包装的时候会从前到后,执行的时候会从后到前。如这里生成的StatementHandler代理对象如下:

总结

加载全部内容

相关教程
猜你喜欢
用户评论