您现在的位置是:首页 > 文章详情

Mybatis 插件原理

日期:2018-08-28点击:541

Mybatis是我们平时常用的ORM框架,它很灵活,在灵活的基础上,我们还可以开发一些Mybatis的插件来实现自己想要的功能。

一起来看下Mybatis插件开发的原理

预备知识

  • JDK的动态代理 Proxy,InvocationHandler
  • 了解Mybatis的基本使用

分析

  1. Mybatis的Configuration对象,存储了mybatis的配置信息,在内部多个地方都可以看到Configuration的影子,这是一个非常重要的对象,在追踪源码的时候可以看到Mybatis插件生效的地方。


    img_711436431dce214dcef3e82db03f4fec.png
    image.png

通过Configration对象,我们看出可以拦截的对象有

  • ResultSetHandler
  • Executor
  • StatementHandler
  • ParameterHandler
  1. 我们看下interceptorChain.pluginAll的内容。


    img_d363f4b8d142845306505fb8a1eacaa7.png
    image.png
  1. 再看下Interceptor接口的内容
public interface Interceptor { // Object intercept(Invocation invocation) throws Throwable; Object plugin(Object target); void setProperties(Properties properties); } // 拦截器的Invocation参数,内部可以封装了target,method, args. 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 proceed() throws InvocationTargetException, IllegalAccessException { return method.invoke(target, args); } } 
  1. 插件的用法,一般的使用方式为
img_79bd8541d311a2bbd052df7bd32935b3.png
image.png
  1. Plugin.wrap内部实现,利用JDK的Proxy实现,参考Java使用Porxy和InvocationHandler实现动态代理

invoke方法中,内部interceptor.intercept(new Invocation(target,method,args))。可以照应开始的Interceptor的接口。


img_635804807861b69fb03aea7e028bf207.png
image.png
  1. Plugin类内部实现了很多有用的工具方法,Interceptor借助Plugin来实现,其内部的方法可以多看一下。

最后

插件的内部实现,看Mybatis的源码就明白怎么回事,其余的再自己内部追踪下。

参考

原文链接:https://yq.aliyun.com/articles/666925
关注公众号

低调大师中文资讯倾力打造互联网数据资讯、行业资源、电子商务、移动互联网、网络营销平台。

持续更新报道IT业界、互联网、市场资讯、驱动更新,是最及时权威的产业资讯及硬件资讯报道平台。

转载内容版权归作者及来源网站所有,本站原创内容转载请注明来源。

文章评论

共有0条评论来说两句吧...

文章二维码

扫描即可查看该文章

点击排行

推荐阅读

最新文章