MyBatis之plugin原理及使用

2018-12-09  本文已影响0人  寒冬的骄阳

实现原理

首先Plugin必须实现Interceptor 常拦截以下类或接口中的方法:

@Intercepts({@Signature(type = Executor.class,
        method ="query",
        args={MappedStatement.class,Object.class,RowBounds.class,ResultHandler.class})})
public class CustomPlugins implements Interceptor {
    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        //最终plugin插件调用的是这个方法
        MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
        BoundSql boundSql = mappedStatement.getBoundSql(invocation.getArgs()[1]);
        System.out.println(String.format("plugin output sql = %s , param=%s", boundSql.getSql(),boundSql.getParameterObject()));
        //放行 该方法
        return invocation.proceed();
    }

    @Override
    public Object plugin(Object o) {
        Object obj= Plugin.wrap(o,this);
        return obj;
    }

    @Override
    public void setProperties(Properties properties) {
        //常用于将配置中的参数赋值给类的实例变量
        String value = (String) properties.get("name");
        System.out.println(value);
    }
}
//InterceptorChain
public class InterceptorChain {

  private final List<Interceptor> interceptors = new ArrayList<Interceptor>();

  public Object pluginAll(Object target) {
    for (Interceptor interceptor : interceptors) {
      //这里的intecetor是Plugin 也即是自定义插件中plugin方法 
      //这里的target是Executor、ParameterHandler、ResultSetHandler、StatementHandler接口的实现类 具体是什么 要看@Interceptors中拦截的接口
      //这里的target是通过for循环不断赋值的,也就是说如果有多个拦截器,那么如果我用P表示代理,生成第       //一次代理为P(target),生成第二次代理为P(P(target)),生成第三次代理为P(P(P(target))),不断      //嵌套下去,这就得到一个重要的结论:<plugins>...</plugins>中后定义的<plugin>实际其拦截器方法     //先被执行,因为根据这段代码来看,后定义的<plugin>代理实际后生成,包装了先生成的代理,自然其代理方     //法也先执行.也即是interceptor的执行顺序 后定义先执行
      //这里的plugin方法实际上是调用对应拦截器类的重载方法
      target = interceptor.plugin(target);
    }
    return target;
  }

  public void addInterceptor(Interceptor interceptor) {
      //添加拦截器至集合
    interceptors.add(interceptor);
  }
 // 列举所有的拦截器类 
  public List<Interceptor> getInterceptors() {
    return Collections.unmodifiableList(interceptors);
  }

}
//Plugin
public static Object wrap(Object target, Interceptor interceptor) {
    //获取拦截器的签名信息,具体代码如下
    Map<Class<?>, Set<Method>> signatureMap = getSignatureMap(interceptor);
    Class<?> type = target.getClass();
    Class<?>[] interfaces = getAllInterfaces(type, signatureMap);
    //如果数组长度大于0 也就是表示type有父接口 可以根据其接口生成代理对象
    if (interfaces.length > 0) {
      return Proxy.newProxyInstance(
          type.getClassLoader(),
          interfaces,
          new Plugin(target, interceptor, signatureMap));
    }
    //否则 返回target对象本身
    return target;
  }

@Override
  public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    try {
        //method#getDeclaringClass() 获取method对应的class类 
        //以CustomPlugin为例,此时method为query 得到的的declaringClass为Executor
        //此时签名Map中可以得到key为Executor的value
      Set<Method> methods = signatureMap.get(method.getDeclaringClass());
      if (methods != null && methods.contains(method)) {
          //这里调用拦截器中的intercept方法 拦截器对应具体的实现 如此时是CustomPlugin
        return interceptor.intercept(new Invocation(target, method, args));
      }
      return method.invoke(target, args);
    } catch (Exception e) {
      throw ExceptionUtil.unwrapThrowable(e);
    }
  }

//getSignatureMap方法

  private static Map<Class<?>, Set<Method>> getSignatureMap(Interceptor interceptor) {
    Intercepts interceptsAnnotation = interceptor.getClass().getAnnotation(Intercepts.class);
    // issue #251
      //如果拦截器类没有Intercepts注解则抛出异常
    if (interceptsAnnotation == null) {
      throw new PluginException("No @Intercepts annotation was found in interceptor " + interceptor.getClass().getName());      
    }
      //以CustomPlugins为例@Intercepts({@Signature(type = Executor.class,
      //method ="query",
    //args={MappedStatement.class,Object.class,RowBounds.class,ResultHandler.class})})
    //type=Executor.class,method=query args=...
    Signature[] sigs = interceptsAnnotation.value();
      //如果存在以type为key的map 则获取其拦截的方法 否则执行map的put方法 为key赋值
    Map<Class<?>, Set<Method>> signatureMap = new HashMap<Class<?>, Set<Method>>();
    for (Signature sig : sigs) {
      Set<Method> methods = signatureMap.get(sig.type());
      if (methods == null) {
        methods = new HashSet<Method>();
        signatureMap.put(sig.type(), methods);
      }
      try {
          //利用反射 获取Executor中方法为query,参数为sig.args的方法
        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);
      }
    }
    //返回签名map
    return signatureMap;
  }
//getInterfaces
private static Class<?>[] getAllInterfaces(Class<?> type, Map<Class<?>, Set<Method>> signatureMap) {
    Set<Class<?>> interfaces = new HashSet<Class<?>>();
    while (type != null) {
        //如此时type为Executor的具体实例 CachingExecutor
        //type.getInterfaces 得到的是Executor
        //刚好Executor.class 为map的key
      for (Class<?> c : type.getInterfaces()) {
        if (signatureMap.containsKey(c)) {
          interfaces.add(c);
        }
      }
        //向上查询 查询其父类
      type = type.getSuperclass();
    }
    return interfaces.toArray(new Class<?>[interfaces.size()]);
  }

使用方式

自定义插件常通过实现Interceptor接口的方式实现

//表示拦截的是哪个类的含有几个参数的方法
@Intercepts({@Signature(type = Executor.class,
        method ="query",
        args={MappedStatement.class,Object.class,RowBounds.class,ResultHandler.class})})
public class CustomPlugins implements Interceptor {
    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        //一系列的操作 然后拦截器放行
        return invocation.proceed();
    }

    @Override
public Object plugin(Object o) {
   //o表示拦截接口的子类 this表示CustomPlugins
        return Plugin.wrap(o,this);
    }

    @Override
    public void setProperties(Properties properties) {
     //读取配置插件时 给出的参数信息
 //常用于将配置中的参数赋值给类的实例变量
        String value = (String) properties.get("name");
        System.out.println(value);
    }
}

配置plugin的两种形式:

//mybatis.xml
<plugins>
  <plugin interceptor="com.wojiushiwo.dal.plugins.CustomPlugins">
    <property name="name" value="wojiushiwo"/>
  </plugin>
</plugins>
//使用的时候直接在注入即可
@Bean
public SqlSessionFactory localSessionFactoryBean() throws Exception {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource);
        //将自定义的typeHandler设置到mybatis配置文件中
        sqlSessionFactoryBean.setTypeHandlers(new TypeHandler[]{new CustomTypeHandler()});
        //将自定义的插件设置到mybatis配置中
        sqlSessionFactoryBean.setPlugins(new Interceptor[]{plugin()});
        SqlSessionFactory factory = sqlSessionFactoryBean.getObject();
        factory.getConfiguration().setLazyLoadingEnabled(true);
        factory.getConfiguration().setAggressiveLazyLoading(false);
        factory.getConfiguration().setProxyFactory(new CglibProxyFactory());
        return factory;
    }

    private Interceptor plugin(){
        CustomPlugins customPlugins=new CustomPlugins();
        Properties properties=new Properties();
        //这里可以设置自定义参数
        properties.setProperty("name","wojiushiwo");
        customPlugins.setProperties(properties);
        return customPlugins;
    }
上一篇 下一篇

猜你喜欢

热点阅读