MyBatis整体预览(二)(关于自己开发插件与mybatis 的整合)

   感谢原文作者分享,原文地址是:http://blog.csdn.net/jdream314/article/details/7473001

MyBatis整体预览(二)

       本文将介绍MyBatis的插件实现原理

         一、MyBatis为开发者提供了非常丰富的接口,以满足开发者扩充自己的功能。将扩展的插件配置到configuration的plugins的标签中,那么mybatis自动将插件插入到你想执行的地方。在《MyBatis整体预览(一)》中,曾介绍MyBatis允许开发者在StatementHandler、ResultSetHandler、ParameterHandler以及Executor插入自己想执行的代码。下面将详细介绍从我们定制自己的插件到插件是如何被调用的来进行分析。

      首先,要开发MyBatis的插件需要实现org.apache.ibatis.plugin.Interceptor接口,这个接口将会要求实现几个方法:intercept()、plugin()及setProperties(),intercept方法是开发人员所要执行的操作,plugin是将你插件放入到MyBatis的插件集合中去,而setProperties这是在你配置你插件的时候将plugins/plugin/properties的值设置到该插件中。这是实现自己插件的几个步骤,注意:一般在plugin方法中只写Plugin.wrap(target,this),target一般是你要拦截的对象,this这是当前的插件,在plugin方法参数中有个plugin(Object target),这个target类型就是StatementHandler、ResultSetHandler、ParameterHandler以及Executor中的一个。这里就插件的基本结构和方法进行了介绍。下面将对MyBatis如何获得开发人员开发的插件,以及具体执行的过程进行分析。

      在《MyBatis整体预览(一)》中,对MyBatis的整个执行过程进行了一个介绍,主要是对Configuration对象的初始化过程进行了比较详细的介绍。当然,在Configuration初始化的过程中当然也包括对开发人员自己的插件进行初始化,并进行保存插件对象。

在XMLConfigBuilder的parsetConfiguration里面调用了pluginElement方法,这个方法将会解析开发人员配置在configuration中的plugin标签下面的元素。执行代码如下:

  1. private void pluginElement(XNode parent) throws Exception {  
  2.    if (parent != null) {  
  3.      for (XNode child : parent.getChildren()) {  
  4.        String interceptor = child.getStringAttribute("interceptor");  
  5.        Properties properties = child.getChildrenAsProperties();  
  6.        Interceptor interceptorInstance = (Interceptor) resolveClass(interceptor).newInstance();  
  7.        interceptorInstance.setProperties(properties);  
  8.        configuration.addInterceptor(interceptorInstance);  
  9.      }  
  10.    }  
  11.   }  

    这个方法里面调用了configuration类中的addInterceptor方法,将插件实例添加到configuration对象中,那么让我们看看configuration里面对插件对象做了什么:

  1. public void addInterceptor(Interceptor interceptor) {  
  2.    interceptorChain.addInterceptor(interceptor);  
  3.   }  

    这就是在configuration类中的这个addInterceptor方法,他将这个插件添加到一个链中,那么这个拦截器链是怎样的呢?

  1. public class InterceptorChain {  
  2.   
  3.   private final List<Interceptor> interceptors = new ArrayList<Interceptor>();  
  4.   
  5.   public Object pluginAll(Object target) {  
  6.     for (Interceptor interceptor : interceptors) {  
  7.       target = interceptor.plugin(target);  
  8.     }  
  9.     return target;  
  10.   }  
  11.   
  12.   public void addInterceptor(Interceptor interceptor) {  
  13.     interceptors.add(interceptor);  
  14.   }  
  15.   
  16.     }  

    这个类很简单,直接将这个插件添加到了一个List对象集合中。你可能会发现上面还有一个pluginAll方法,并且在该方法里面调用了插件的plugin方法。大家是否明白了,这个plugin方法里面上面已经介绍,只是执行了Plugin.wrap(target,this)段代码。那么现在就有个几个问题:第一、这个pluginAll方法什么时候调用,还有就是Plugin.wrap(target,this),这段代码是干什么用的。理解清楚这两个问题,那么MyBatis的插件开发过程就完全理解了。

    首先让我们开看看如何调用pluginAll方法的。在Configuration类中会发现一下几个方法:

  1. public ParameterHandler newParameterHandler(MappedStatement mappedStatement, Object parameterObject, BoundSql boundSql) {  
  2.     ParameterHandler parameterHandler = new DefaultParameterHandler(mappedStatement, parameterObject, boundSql);  
  3.     parameterHandler = (ParameterHandler) interceptorChain.pluginAll(parameterHandler);  
  4.     return parameterHandler;  
  5.   }  
  6.   
  7.   public ResultSetHandler newResultSetHandler(Executor executor, MappedStatement mappedStatement, RowBounds rowBounds, ParameterHandler parameterHandler,  
  8.       ResultHandler resultHandler, BoundSql boundSql) {  
  9.     ResultSetHandler resultSetHandler = mappedStatement.hasNestedResultMaps() ? new NestedResultSetHandler(executor, mappedStatement, parameterHandler, resultHandler, boundSql,  
  10.         rowBounds) : new FastResultSetHandler(executor, mappedStatement, parameterHandler, resultHandler, boundSql, rowBounds);  
  11.     resultSetHandler = (ResultSetHandler) interceptorChain.pluginAll(resultSetHandler);  
  12.     return resultSetHandler;  
  13.   }  
  14.   
  15.   public StatementHandler newStatementHandler(Executor executor, MappedStatement mappedStatement, Object parameterObject, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) {  
  16.     StatementHandler statementHandler = new RoutingStatementHandler(executor, mappedStatement, parameterObject, rowBounds, resultHandler, boundSql);  
  17.     statementHandler = (StatementHandler) interceptorChain.pluginAll(statementHandler);  
  18.     return statementHandler;  
  19.       }  
  20.   public Executor newExecutor(Transaction transaction, ExecutorType executorType, boolean autoCommit) {  
  21.     executorType = executorType == null ? defaultExecutorType : executorType;  
  22.     executorType = executorType == null ? ExecutorType.SIMPLE : executorType;  
  23.     Executor executor;  
  24.     if (ExecutorType.BATCH == executorType) {  
  25.       executor = new BatchExecutor(this, transaction);  
  26.     } else if (ExecutorType.REUSE == executorType) {  
  27.       executor = new ReuseExecutor(this, transaction);  
  28.     } else {  
  29.       executor = new SimpleExecutor(this, transaction);  
  30.     }  
  31.     if (cacheEnabled) {  
  32.       executor = new CachingExecutor(executor, autoCommit);  
  33.     }  
  34.     executor = (Executor) interceptorChain.pluginAll(executor);  
  35.     return executor;  
  36.       }  

    可以很清楚看到这几个方法里面都调用了pluginAll方法。看了这几个方法名不用我解释这些方法是做什么的了吧?这就是我为什么说:MyBatis允许开发者在StatementHandlerResultSetHandlerParameterHandler以及Executor插入自己想执行的代码。pluginAll都是将new出来的对象传递过去,这就是target。这里就对pluginAll方法进行了介绍。那么接下来就对插件的核心部分进行介绍。

    Plugin.wrap(target,this)这段代码是做了什么事?在这里我将为大家解开这神秘的面纱。首先看看wrap方法是做了什么:

  1. public static Object wrap(Object target, Interceptor interceptor) {  
  2.     Map<Class<?>, Set<Method>> signatureMap = getSignatureMap(interceptor);  
  3.     Class<?> type = target.getClass();  
  4.     Class<?>[] interfaces = getAllInterfaces(type, signatureMap);  
  5.     if (interfaces.length > 0) {  
  6.       return Proxy.newProxyInstance(  
  7.           type.getClassLoader(),  
  8.           interfaces,  
  9.           new Plugin(target, interceptor, signatureMap));  
  10.     }  
  11.     return target;  
  12.       }  

    这个方法有来两个参数,第一个是target,第二个是interceptortarget就是我们要拦截的对象,及就是我们插件要放入到那个对象的代码中去,而interceptor就是开发人员开发的插件对象,此处貌似叫插件不是很合里,叫做拦截器更为合理,因为他是拦截MyBatis的执行过程,从而插入开发人员自己想执行的代码。此处就不就此问题纠结太久。发现在wrap方法里面第一行就调用了getSignatureMap方法,看到Signature这个单词不知是否很熟悉,这个在我们定义自己插件的时候貌似用到了:

  1. @Intercepts( {@Signature(type = StatementHandler.class, method = "prepare", args = {Connection.class})})  
  2. public class StatementHandlerInterceptor implements Interceptor {  
  3.     private String DIALECT ;  
  4.     public String getDIALECT() {  
  5.         return DIALECT;  
  6.     }  
  7.   
  8.     public void setDIALECT(String dIALECT) {  
  9.         DIALECT = dIALECT;  
  10.     }  
  11.   
  12.     @Override  
  13.     public Object intercept(Invocation invocation) throws Throwable {  
  14.   
  15.         RoutingStatementHandler statement = (RoutingStatementHandler)invocation.getTarget();  
  16.         PreparedStatementHandler handler = (PreparedStatementHandler)ReflectUtil.getFieldValue(statement,  
  17.                 "delegate");  
  18.         RowBounds rowBounds = (RowBounds)ReflectUtil.getFieldValue(handler,  
  19.                 "rowBounds");  
  20.         if(rowBounds!=null)  
  21.         {  
  22.         if (rowBounds.getLimit() > 0  
  23.                 && rowBounds.getLimit() < RowBounds.NO_ROW_LIMIT)  
  24.         {  
  25.             BoundSql boundSql = statement.getBoundSql();  
  26.             String sql = boundSql.getSql();  
  27.             Dialect dialect = (Dialect)Class.forName(DIALECT).newInstance();  
  28.             sql = dialect.getLimitString(sql,  
  29.                     rowBounds.getOffset(),  
  30.                     rowBounds.getLimit());  
  31.             ReflectUtil.setFieldValue(boundSql, "sql", sql);  
  32.         }  
  33.         }  
  34.         return invocation.proceed();  
  35.     }  
  36.   
  37.     @Override  
  38.     public Object plugin(Object target) {  
  39.         return Plugin.wrap(target, this);  
  40.     }  
  41.   
  42.     @Override  
  43.     public void setProperties(Properties arg0) {  
  44.   
  45.     }  
  46.   
  47.     }  

    上面那段代码是我实现的一个拦截StatementHandlerprepare方法的插件。看到我在配置拦截目标的时候用到了这样一个注解:

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

这里面有个@Signature注解,这个单词是否和我上面讲到的一个方法名中包含这个单词。对,就是getSignatureMap这个方法。可以很容易想到这个方法就是处理这个注解的。接下来展开看一下getSignatureMap方法所要执行的操作。

  1. private static Map<Class<?>, Set<Method>> getSignatureMap(Interceptor interceptor) {  
  2.   
  3.     Intercepts interceptsAnnotation = interceptor.getClass().getAnnotation(Intercepts.class);  
  4.   
  5.     if (interceptsAnnotation == null) { // issue #251  
  6.   
  7.       throw new PluginException("No @Intercepts annotation was found in interceptor " + interceptor.getClass().getName());        
  8.   
  9.     }  
  10.   
  11.     Signature[] sigs = interceptsAnnotation.value();  
  12.   
  13.     Map<Class<?>, Set<Method>> signatureMap = new HashMap<Class<?>, Set<Method>>();  
  14.   
  15.     for (Signature sig : sigs) {  
  16.   
  17.       Set<Method> methods = signatureMap.get(sig.type());  
  18.   
  19.       if (methods == null) {  
  20.   
  21.         methods = new HashSet<Method>();  
  22.   
  23.         signatureMap.put(sig.type(), methods);  
  24.   
  25.       }  
  26.   
  27.       try {  
  28.   
  29.         Method method = sig.type().getMethod(sig.method(), sig.args());  
  30.   
  31.         methods.add(method);  
  32.   
  33.       } catch (NoSuchMethodException e) {  
  34.   
  35.         throw new PluginException("Could not find method on " + sig.type() + " named " + sig.method() + ". Cause: " + e, e);  
  36.   
  37.       }  
  38.   
  39.     }  
  40.   
  41.     return signatureMap;  
  42.   
  43.   }  

    该方法的第一句话就是获得Intercepts注解,这种方法应该很容易理解。那么接下来将获得在Intercepts里面的参数@Signature注解内容,在该注解中包含三个参数,分别是typemethodargsType指定要拦截的类对象,method是指明要拦截该类的哪个方法,第三个是指明要拦截的方法参数集合。在Intercepts中可以配置多个@Signature。那么便对这写值进行遍历,已获得对应的typemethod以及args。最终是获得一个HashMap对象,这些对象里面的键是类对象,而值是指定的类中方法对象。执行该端程序之后,更具targetclassLoader和接口,来创建一个代理,并且,InvocationHandler是创建一个新的Plugin对象,同时将targetinterceptor以及signatureMap传递给Plugin对象,当然,这里的Plugin也实现了Invocation接口。那么target对象所有的方法调用都会触发Plugin中的invoke方法,那么这里将执行开发者所有插入的操作。

  1. public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {  
  2.    try {  
  3.      Set<Method> methods = signatureMap.get(method.getDeclaringClass());  
  4.      if (methods != null && methods.contains(method)) {  
  5.        return interceptor.intercept(new Invocation(target, method, args));  
  6.      }  
  7.      return method.invoke(target, args);  
  8.    } catch (Exception e) {  
  9.      throw ExceptionUtil.unwrapThrowable(e);  
  10.    }  
  11.   }  

    发现,此处将判断,复合拦截要求的将执行插件的intercept方法,而在intercept方法里面放入了开发者所要执行的操作。那么此时,就成功的调用了开发者开发的MyBatis的插件了。现在来梳理一下执行的过程。

    首先,开发者需要实现MyBatisInterceptor接口,并主要要实现interceptorplugin方法,而setProperties()当你配置了property就需要实现,没有,那么可以不用实现。实现接口后,那么就要将插件配置到MyBatis中去,然后通过XMLConfigBuilder来实例化插件对象,并将他们放到Configuration对象的InterceptChain对象的List集合中,然后在Configuration各种new的方法中调用InterceptChainpluginAll方法,这里面将调用各个插件的plugin方法,这个方法里面则就调用Pluginwrap方法,这个方法将要传入targetthis(也就是插件自身对象)。那么在Plugin对象里面将创建一个代理对象,并且为这个代理对象创建一个InvocationHandler对象,这里将拦截代理对象的所有方法执行过程,及触发invoke方法,这里将执行实现的插件行为。这就是MyBatis的插件实现以及执行的过程。可能其中存在很多疑惑,但大致的流程应该都有,希望能够给大家带来帮助。

    本文到此已结束!后期有时间也会发布关于MyBatis的相关内容!如有不对还望大家指出!大家相互学习,相互进步!


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值