MyBatis插件及开发过程

一、简介

     SqlSession包含四大对象,可以在四大对象调度的时候插入自定义的代码,以满足特殊的需求,这便是MyBatis提供的插件技术。有些特殊场景,需要使用插件统一处理,比如:在进行多租户开发时,数据要按租户隔离,可以在sql语句后面统一添加租户编号筛选条件。

二、插件的接口和初始化分析

1、插件接口:在MyBatis中使用插件,需要实现Interceptor接口,定义如下:

public interface Interceptor {
  Object intercept(Invocation invocation) throws Throwable;
  
  Object plugin(Object target);
  
  void setProperties(Properties properties);
}

详细说说这3个方法:

  • intercept:它将直接覆盖你所拦截的对象,有个参数Invocation对象,通过该对象,可以反射调度原来对象的方法;
  • plugin:target是被拦截的对象,它的作用是给被拦截对象生成一个代理对象;
  • setProperties:允许在plugin元素中配置所需参数,该方法在插件初始化的时候会被调用一次;

2、插件初始化

     插件的初始化时在MyBatis初始化的时候完成的,读入插件节点和配置的参数,使用反射技术生成插件实例,然后调用插件方法中的setProperties方法设置参数,并将插件实例保存到配置对象中,具体过程看下面代码。

<plugins>
    <plugin interceptor="com.qqdong.study.mybatis.TenantPlugin">
        <property name="dbType" value="mysql"/>
    </plugin>
<plugins>

插件初始化过程:

public class XMLConfigBuilder extends BaseBuilder {
  ......
  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);
      }
    }
  }
  ......
}

配置对象Configuration的添加插件方法:

public class Configuration {
  protected final InterceptorChain interceptorChain = new InterceptorChain();
  public void addInterceptor(Interceptor interceptor) {
    interceptorChain.addInterceptor(interceptor);
  }
}

InterceptorChain是一个类,主要包含一个List属性,保存Interceptor对象:

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);
  }
}

3、插件的代理和反射设计原理

3.1 责任链模式

     插件用的是责任链模式,责任链模式是一种对象行为模式。在责任链模式里,很多对象由每一个对象对其下家的引用而连接起来形成一条链,请求在这个链上传递,直到链上的某一个对象决定处理此请求。

3.2 设计细节

前面提到了InterceptorChain类,其中有个pluginAll方法,责任链就是在该方法定义的

public Object pluginAll(Object target) {
    for (Interceptor interceptor : interceptors) {
      target = interceptor.plugin(target);
    }
    return target;
}

上面介绍过plugin方法,它是生成代理对象的方法,从第一个对象(四大对象中的一个)开始,将对象传递给了plugin方法,返回一个代理;如果存在第二个插件,就拿着第一个代理对象,传递给plugin方法,返回第一个代理对象的代理.....

plugin方法是需要我们去实现的,如何生成代理类呢,MyBatis提供了Plugin工具类,它实现了InvocationHandler接口(JDK动态代理的接口),看看它的2个方法:

public class Plugin implements InvocationHandler {
  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;
  }

  @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);
    }
  }
}

     分析下这块代码,Plugin提供了静态方法wrap方法,它会根据插件的签名配置,使用JDK动态代理的方法,生成一个代理类当四大对象执行方法时,会调用Plugin的invoke方法,如果方法包含在声明的签名里,就会调用自定义插件的intercept方法,传入Invocation对象。

     另外,Invocation对象包含一个proceed方法,这个方法就是调用被代理对象的真实方法,如果有n个插件,第一个传递的参数是四大对象本身,然后调用一次wrap方法产生第一个代理对象,这里的反射就是四大对象的真实方法,如果有第二个插件,这里的反射就是第一个代理对象的invoke方法。

     所以,在多个插件的情况下,调度proceed方法,MyBatis总是从最后一个代理对象运行到第一个代理对象,最后是真实被拦截的对象方法被执行。

4、工具类MetaObject介绍

     MetaObject是MyBatis给我们提供的工具类,它可以有效的获取或修改一些重要对象的属性。

5、最后总结下插件的开发步骤

5.1 确定要拦截的签名

  • 确定要拦截的对象,四大对象之一;
  • 确定拦截的方法和参数;

比如想拦截StatementHandler对象的prepare方法,该方法有一个参数Connection对象,可以这样声明:

@Intercepts({
    @Signature(type =StatementHandler.class,
        method="prepare" , 
        args={Connection.class})})
public class MyPlugin implements Interceptor{
    ......
}

5.2 定义插件类,实现拦截方法

   上面已经分析过原理,实现Interceptor接口的方法即可,通过Plugin工具类方便生成代理类,通过MetaObject工具类方便操作四大对象的属性,修改对应的值。

5.3 配置

<plugins>
    <plugin interceptor="com.qqdong.study.mybatis.TenantPlugin">
        <property name="dbType" value="mysql"/>
    </plugin>
<plugins>

自定义插件还是比较复杂的,如果不了解原理,很容易出错,能不用插件尽量不要使用,因为它是修改MyBatis的底层设计。 插件生成的是层层代理对象的责任链模式,通过反射方法运行,性能不高,要考虑全面,特别是多个插件层层代理的逻辑。


 

 

 

 

 

 

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值