SqlSession的运行依赖四大组件:Executor,StatementHandler,ParameterHandler,ResultSetHandler,由四个组件调度完成sql的调用过程。Mybatis的插件就是在四个组件的调用过程中插入我们需要的代码来完成我们特殊的需求。
首先根据功能来确定需要拦截的的对象
- Executor:执行SQL的全过程,包括组装参数,组装结果集返回和执行SQL过程,都可以拦截,较为广泛;
- StatementHandler:是执行的过程,我们可以重写执行SQL的过程。这是我们最常用的拦截对象;
- ParameterHandler:拦截执行SQL的参数组装,可以重写参数组装规则;
- ResultSetHandler:用于拦截执行结果的组装,可以重写组装结果的规则。
Mybatis的插件实现通过以下的类实现
- Interceptor:拦截接口,拦截代码的实现接口,其中完成我们具体的拦截逻辑
- InterceptorChain:拦截链,包含所有的拦截实现
- Intercepts:拦截注解,Mybatis扫描此注解,确定拦截类
- Signature:拦截的方法签名,作为Intercepts的值,只有签名的对象和方法才会被拦截。
- Invocation:被拦截的对象的封装
- Plugin:插件类,插件通过动态代理模式实现,由Plugin实现
在编写插件过程中我们会使用到Interceptor,Intercepts,Invocation,Singnature.
插件运行
//Configuration中四个组件应用插件
public ParameterHandler newParameterHandler(MappedStatement mappedStatement, Object parameterObject, BoundSql boundSql) {
ParameterHandler parameterHandler = mappedStatement.getLang().createParameterHandler(mappedStatement, parameterObject, boundSql);
//ParameterHandler 应用插件
parameterHandler = (ParameterHandler) interceptorChain.pluginAll(parameterHandler);
return parameterHandler;
}
public ResultSetHandler newResultSetHandler(Executor executor, MappedStatement mappedStatement, RowBounds rowBounds, ParameterHandler parameterHandler,
ResultHandler resultHandler, BoundSql boundSql) {
ResultSetHandler resultSetHandler = new DefaultResultSetHandler(executor, mappedStatement, parameterHandler, resultHandler, boundSql, rowBounds);
//ResultSetHandler 应用插件
resultSetHandler = (ResultSetHandler) interceptorChain.pluginAll(resultSetHandler);
return resultSetHandler;
}
public StatementHandler newStatementHandler(Executor executor, MappedStatement mappedStatement, Object parameterObject, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) {
StatementHandler statementHandler = new RoutingStatementHandler(executor, mappedStatement, parameterObject, rowBounds, resultHandler, boundSql);
//StatementHandler 应用插件
statementHandler = (StatementHandler) interceptorChain.pluginAll(statementHandler);
return statementHandler;
}
public Executor newExecutor(Transaction transaction) {
return newExecutor(transaction, defaultExecutorType);
}
public Executor newExecutor(Transaction transaction, ExecutorType executorType) {
executorType = executorType == null ? defaultExecutorType : executorType;
executorType = executorType == null ? ExecutorType.SIMPLE : executorType;
Executor executor;
if (ExecutorType.BATCH == executorType) {
executor = new BatchExecutor(this, transaction);
} else if (ExecutorType.REUSE == executorType) {
executor = new ReuseExecutor(this, transaction);
} else {
executor = new SimpleExecutor(this, transaction);
}
if (cacheEnabled) {
executor = new CachingExecutor(executor);
}
//Executor 应用插件
executor = (Executor) interceptorChain.pluginAll(executor);
return executor;
}
在Configuration中new出四个组件实例的时候都会获取对应的插件。
从pluginAll作为入口进行分析:
//InterceptorChain#pluginAll
//target 被代理的对象
public Object pluginAll(Object target) {
//循环判断是否符合拦截情况
for (Interceptor interceptor : interceptors) {
target = interceptor.plugin(target);
}
//如果有匹配成功,target为jdk生成的动态代理对象
return target;
}
//简单实例出一个拦截器
@Intercepts(
{
//拦截的方法签名,对应方法为Executor#query(MappedStatement statement,Object object,RowBounds rowBounds,ResultHandler resultHandler)
@Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class}),
//对应方法为Executor#query(MappedStatement statement,Object object,RowBounds rowBounds,ResultHandler resultHandler,CacheKey cacheKey,BoundSql boundSql)
@Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class, CacheKey.class, BoundSql.class}),
}
)
public class MyInterceptor implements Interceptor {
@Override
public Object intercept(Invocation invocation) {
//拦截后的需要实现的逻辑
return invocation.proceed();
}
//Interceptor的实现类,插件的引用由Plugin来完成
@Override
public Object plugin(Object target) {
//target:被代理的对象,this:拦截器本对象
return Plugin.wrap(target, this);
}
@Override
public void setProperties(Properties properties) {
}
}
// Plugin#wrap 利用动态代理模式,生成被代理对象(Executor,StatementHandler,ResultSetHandler,ParameterHandler)的代理类
public static Object wrap(Object target, Interceptor interceptor) {
//获取拦截器(interceptor)的签名方法,获取到的MyInterceptor的签名为key:Executor.class ;value:[query1(),query2()]
Map<Class<?>, Set<Method>> signatureMap = getSignatureMap(interceptor);
//被拦截对象的class类型
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;
}
//Plugin 实现了jdk动态代理的InvocationHandler接口
//Plugin#invoke 运行时调用的接口
@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)) {
//包装成Invocation(target, method, args)对象,由拦截器执行,即我们自己的拦截逻辑
//target:被拦截的对象,method:方法对象,args:方法参数
return interceptor.intercept(new Invocation(target, method, args));
}
return method.invoke(target, args);
} catch (Exception e) {
throw ExceptionUtil.unwrapThrowable(e);
}
}
总结
mybatis的插件的原理:利用动态代理模式对四个组件进行拦截,以实现在调用过程中加入特殊的需求。