前景回顾
第一节 从零开始手写 mybatis(一)MVP 版本 中咱们实现了一个最根本的能够运行的 mybatis。
常言道,万事开头难,而后两头难。
mybatis 的插件机制是 mybatis 除却动静代理之外的第二大灵魂。
上面咱们一起来体验一下这乏味的灵魂带来的苦楚与高兴~
插件的作用
在理论开发过程中,咱们常常应用的Mybaits插件就是分页插件了,通过分页插件咱们能够在不必写count语句和limit的状况下就能够获取分页后的数据,给咱们开发带来很大
的便当。除了分页,插件应用场景次要还有更新数据库的通用字段,分库分表,加解密等的解决。
这篇博客次要讲Mybatis插件原理,下一篇博客会设计一个Mybatis插件实现的性能就是每当新增数据的时候不必数据库自增ID而是通过该插件生成雪花ID,作为每条数据的主键。
JDK动静代理+责任链设计模式
Mybatis的插件其实就是个拦截器性能。它利用JDK动静代理和责任链设计模式的综合使用。采纳责任链模式,通过动静代理组织多个拦截器,通过这些拦截器你能够做一些你想做的事。
所以在讲Mybatis拦截器之前咱们先说说JDK动静代理+责任链设计模式。
JDK 动静代理案例
package com.github.houbb.mybatis.plugin;import java.lang.reflect.InvocationHandler;import java.lang.reflect.Method;import java.lang.reflect.Proxy;public class JdkDynamicProxy { /** * 一个接口 */ public interface HelloService{ void sayHello(); } /** * 指标类实现接口 */ static class HelloServiceImpl implements HelloService{ @Override public void sayHello() { System.out.println("sayHello......"); } } /** * 自定义代理类须要实现InvocationHandler接口 */ static class HelloInvocationHandler implements InvocationHandler { private Object target; public HelloInvocationHandler(Object target){ this.target = target; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { System.out.println("------插入前置告诉代码-------------"); //执行相应的指标办法 Object rs = method.invoke(target,args); System.out.println("------插入后置解决代码-------------"); return rs; } public static Object wrap(Object target) { return Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(),new HelloInvocationHandler(target)); } } public static void main(String[] args) { HelloService proxyService = (HelloService) HelloInvocationHandler.wrap(new HelloServiceImpl()); proxyService.sayHello(); }}
- 输入
------插入前置告诉代码-------------sayHello......------插入后置解决代码-------------
优化1:面向对象
下面代理的性能是实现了,然而有个很显著的缺点,就是 HelloInvocationHandler 是动静代理类,也能够了解成是个工具类,咱们不可能会把业务代码写到写到到invoke办法里,
不合乎面向对象的思维,能够形象一下解决。
定义接口
能够设计一个Interceptor接口,须要做什么拦挡解决实现接口就行了。
public interface Interceptor { /** * 具体拦挡解决 */ void intercept();}
实现接口
public class LogInterceptor implements Interceptor{ @Override public void intercept() { System.out.println("------插入前置告诉代码-------------"); }}
和
public class TransactionInterceptor implements Interceptor{ @Override public void intercept() { System.out.println("------插入后置解决代码-------------"); }}
实现代理
public class InterfaceProxy implements InvocationHandler { private Object target; private List<Interceptor> interceptorList = new ArrayList<>(); public InterfaceProxy(Object target, List<Interceptor> interceptorList) { this.target = target; this.interceptorList = interceptorList; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { //解决多个拦截器 for (Interceptor interceptor : interceptorList) { interceptor.intercept(); } return method.invoke(target, args); } public static Object wrap(Object target, List<Interceptor> interceptorList) { InterfaceProxy targetProxy = new InterfaceProxy(target, interceptorList); return Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(), targetProxy); } }
测试验证
public static void main(String[] args) { List<Interceptor> interceptorList = new ArrayList<>(); interceptorList.add(new LogInterceptor()); interceptorList.add(new TransactionInterceptor()); HelloService target = new HelloServiceImpl(); HelloService targetProxy = (HelloService) InterfaceProxy.wrap(target, interceptorList); targetProxy.sayHello();}
- 日志
------插入前置告诉代码-------------------插入后置解决代码-------------sayHello......
这里有一个很显著的问题,所有的拦挡都在办法执行前被解决了。
优化 2:灵便指定前后
下面的动静代理的确能够把代理类中的业务逻辑抽离进去,然而咱们留神到,只有前置代理,无奈做到前后代理,所以还须要在优化下。
所以须要做更一步的形象,
把拦挡对象信息进行封装,作为拦截器拦挡办法的参数,把拦挡指标对象真正的执行办法放到Interceptor中实现,这样就能够实现前后拦挡,并且还能对拦挡对象的参数等做批改。
实现思路
代理类上下文
设计一个 Invocation 对象。
public class Invocation { /** * 指标对象 */ private Object target; /** * 执行的办法 */ private Method method; /** * 办法的参数 */ private Object[] args; public Invocation(Object target, Method method, Object[] args) { this.target = target; this.method = method; this.args = args; } /** * 执行指标对象的办法 */ public Object process() throws Exception{ return method.invoke(target,args); } // 省略 Getter/Setter}
调整接口
- Interceptor.java
public interface Interceptor { /** * 具体拦挡解决 */ Object intercept(Invocation invocation) throws Exception;}
- 日志实现
public class MyLogInterceptor implements Interceptor { @Override public Object intercept(Invocation invocation) throws Exception { System.out.println("------插入前置告诉代码-------------"); Object result = invocation.process(); System.out.println("------插入后置解决代码-------------"); return result; }}
从新实现代理类
public class MyInvocationHandler implements InvocationHandler { private Object target; private Interceptor interceptor; public MyInvocationHandler(Object target, Interceptor interceptor) { this.target = target; this.interceptor = interceptor; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { Invocation invocation = new Invocation(target, method, args); // 返回的仍然是代理类的后果 return interceptor.intercept(invocation); } public static Object wrap(Object target, Interceptor interceptor) { MyInvocationHandler targetProxy = new MyInvocationHandler(target, interceptor); return Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(), targetProxy); }}
最外围的就在于构建了 invocation,而后执行对应的办法。
测试
- 代码
public static void main(String[] args) { HelloService target = new HelloServiceImpl(); Interceptor interceptor = new MyLogInterceptor(); HelloService targetProxy = (HelloService) MyInvocationHandler.wrap(target, interceptor); targetProxy.sayHello();}
- 日志
------插入前置告诉代码-------------sayHello......------插入后置解决代码-------------
优化 3:划清界限
下面这样就能实现前后拦挡,并且拦截器能获取拦挡对象信息。
然而测试代码的这样调用看着很顺当,对应指标类来说,只须要理解对他插入了什么拦挡就好。
再批改一下,在拦截器减少一个插入指标类的办法。
实现
接口调整
public interface Interceptor { /** * 具体拦挡解决 * * @return 办法执行的后果 * @since 0.0.2 */ Object intercept(Invocation invocation) throws Exception; /** * 插入指标类 * * @return 代理 * @since 0.0.2 */ Object plugin(Object target);}
实现调整
能够了解为把静态方法调整为对象办法。
public class MyLogInterceptor implements Interceptor { @Override public Object intercept(Invocation invocation) throws Exception { System.out.println("------插入前置告诉代码-------------"); Object result = invocation.process(); System.out.println("------插入后置解决代码-------------"); return result; } @Override public Object plugin(Object target) { return MyInvocationHandler.wrap(target, this); }}
测试
- 代码
public static void main(String[] args) { HelloService target = new HelloServiceImpl(); Interceptor interceptor = new MyLogInterceptor(); HelloService targetProxy = (HelloService) interceptor.plugin(target); targetProxy.sayHello();}
- 日志
------插入前置告诉代码-------------sayHello......------插入后置解决代码-------------
责任链模式
多个拦截器如何解决?
测试代码
public static void main(String[] args) { HelloService target = new HelloServiceImpl(); //1. 拦截器1 Interceptor interceptor = new MyLogInterceptor(); target = (HelloService) interceptor.plugin(target); //2. 拦截器 2 Interceptor interceptor2 = new MyTransactionInterceptor(); target = (HelloService) interceptor2.plugin(target); // 调用 target.sayHello();}
其中 MyTransactionInterceptor 实现如下:
public class MyTransactionInterceptor implements Interceptor { @Override public Object intercept(Invocation invocation) throws Exception { System.out.println("------tx start-------------"); Object result = invocation.process(); System.out.println("------tx end-------------"); return result; } @Override public Object plugin(Object target) { return MyInvocationHandler.wrap(target, this); }}
日志如下:
------tx start-------------------插入前置告诉代码-------------sayHello......------插入后置解决代码-------------------tx end-------------
当然很多小伙伴看到这里其实曾经想到应用责任链模式,上面咱们一起来看一下责任链模式。
责任链模式
责任链模式
public class InterceptorChain { private List<Interceptor> interceptorList = new ArrayList<>(); /** * 插入所有拦截器 */ public Object pluginAll(Object target) { for (Interceptor interceptor : interceptorList) { target = interceptor.plugin(target); } return target; } public void addInterceptor(Interceptor interceptor) { interceptorList.add(interceptor); } /** * 返回一个不可批改汇合,只能通过addInterceptor办法增加 * 这样控制权就在本人手里 */ public List<Interceptor> getInterceptorList() { return Collections.unmodifiableList(interceptorList); }}
测试
public static void main(String[] args) { HelloService target = new HelloServiceImpl(); Interceptor interceptor = new MyLogInterceptor(); Interceptor interceptor2 = new MyTransactionInterceptor(); InterceptorChain chain = new InterceptorChain(); chain.addInterceptor(interceptor); chain.addInterceptor(interceptor2); target = (HelloService) chain.pluginAll(target); // 调用 target.sayHello();}
- 日志
------tx start-------------------插入前置告诉代码-------------sayHello......------插入后置解决代码-------------------tx end-------------
集体的思考
拦截器是否能够改良?
实际上个人感觉这里能够换一种角度,比方定义拦截器接口时,改为:
这样能够代码中能够不必写执行的局部,实现起来更加简略,也不会遗记。
public interface Interceptor { /** * 具体拦挡解决 */ void before(Invocation invacation); /** * 具体拦挡解决 */ void after(Invocation invacation);}
不过这样也有一个毛病,那就是对于 process 执行的局部不可见,丢失了一部分灵活性。
形象实现
对于 plugin() 这个办法,实际上实现十分固定。
应该对于接口不可见,间接放在 chain 中对立解决即可。
手写 mybatis 引入插件
说了这么多,如果你了解之后,那么接下来的插件实现局部就是小菜一碟。
只是将下面的思维做一个简略的实现而已。
疾速体验
config.xml
引入插件,其余局部省略。
<plugins> <plugin interceptor="com.github.houbb.mybatis.plugin.SimpleLogInterceptor"/></plugins>
SimpleLogInterceptor.java
咱们就是简略的输入一下入参和出参。
public class SimpleLogInterceptor implements Interceptor{ @Override public void before(Invocation invocation) { System.out.println("----param: " + Arrays.toString(invocation.getArgs())); } @Override public void after(Invocation invocation, Object result) { System.out.println("----result: " + result); }}
执行测试方法
输入日志如下。
----param: [com.github.houbb.mybatis.config.impl.XmlConfig@3b76982e, MapperMethod{type='select', sql='select * from user where id = ?', methodName='selectById', resultType=class com.github.houbb.mybatis.domain.User, paramType=class java.lang.Long}, [Ljava.lang.Object;@67011281]----result: User{id=1, name='luna', password='123456'}User{id=1, name='luna', password='123456'}
是不是灰常的简略,那么是怎么实现的呢?
外围实现
接口定义
public interface Interceptor { /** * 前置拦挡 * @param invocation 上下文 * @since 0.0.2 */ void before(Invocation invocation); /** * 后置拦挡 * @param invocation 上下文 * @param result 执行后果 * @since 0.0.2 */ void after(Invocation invocation, Object result);}
启动插件
在 openSession() 的时候,咱们启动插件:
public SqlSession openSession() { Executor executor = new SimpleExecutor(); //1. 插件 InterceptorChain interceptorChain = new InterceptorChain(); List<Interceptor> interceptors = config.getInterceptorList(); interceptorChain.add(interceptors); executor = (Executor) interceptorChain.pluginAll(executor); //2. 创立 return new DefaultSqlSession(config, executor);}
这里咱们就看到了一个责任链,实现如下。
责任链
public class InterceptorChain { /** * 拦截器列表 * @since 0.0.2 */ private final List<Interceptor> interceptorList = new ArrayList<>(); /** * 增加拦截器 * @param interceptor 拦截器 * @return this * @since 0.0.2 */ public synchronized InterceptorChain add(Interceptor interceptor) { interceptorList.add(interceptor); return this; } /** * 增加拦截器 * @param interceptorList 拦截器列表 * @return this * @since 0.0.2 */ public synchronized InterceptorChain add(List<Interceptor> interceptorList) { for(Interceptor interceptor : interceptorList) { this.add(interceptor); } return this; } /** * 代理所有 * @param target 指标类 * @return 后果 * @since 0.0.2 */ public Object pluginAll(Object target) { for(Interceptor interceptor : interceptorList) { target = DefaultInvocationHandler.proxy(target, interceptor); } return target; }}
其中的 DefaultInvocationHandler 实现如下:
/** * 默认的代理实现 * @since 0.0.2 */public class DefaultInvocationHandler implements InvocationHandler { /** * 代理类 * @since 0.0.2 */ private final Object target; /** * 拦截器 * @since 0.0.2 */ private final Interceptor interceptor; public DefaultInvocationHandler(Object target, Interceptor interceptor) { this.target = target; this.interceptor = interceptor; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { Invocation invocation = new Invocation(target, method, args); interceptor.before(invocation); // invoke Object result = method.invoke(target, args); interceptor.after(invocation, result); return result; } /** * 构建代理 * @param target 指标对象 * @param interceptor 拦截器 * @return 代理 * @since 0.0.2 */ public static Object proxy(Object target, Interceptor interceptor) { DefaultInvocationHandler targetProxy = new DefaultInvocationHandler(target, interceptor); return Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(), targetProxy); }}
小结
本节的实现并不难,难在要了解 mybatis 整体对于插件的设计理念,技术层面还是动静代理,联合了责任链的设计模式。
这种套路学会之后,其实很多相似的框架,咱们本人在实现的时候都能够借鉴这种思维。
拓展浏览
从零开始手写 mybatis(一)MVP 版本
参考资料
Mybatis框架(8)---Mybatis插件原理(代理+责任链)