插件机制主要组件类:
org.apache.ibatis.plugin.Interceptor
org.apache.ibatis.plugin.InterceptorChain
org.apache.ibatis.executor.parameter.ParameterHandler
org.apache.ibatis.executor.resultset.ResultSetHandler
org.apache.ibatis.executor.statement.StatementHandler
org.apache.ibatis.executor.Executor
org.apache.ibatis.session.Configuration
org.apache.ibatis.plugin.Plugin
org.apache.ibatis.plugin.Intercepts
org.apache.ibatis.plugin.Signature
吐槽 : mybatis 的插件机制乍一看是很啃爹的 , 刚看到 Interceptor 这个接口的时候根本不知道该怎么玩 。然后看文档,文档上的列子写的比较详细了,看了之后知道该如何使用了,但是还是有不少疑问。这些疑问就只能通过看源码来找到答案了。
Configuration 中有4个地方用到了 InterceptorChain 的 pluginAll 方法:
newParameterHandler ; newResultSetHandler ; newStatementHandler ; newExecutor ;
public ParameterHandler newParameterHandler(MappedStatement mappedStatement, Object parameterObject, BoundSql boundSql) {
ParameterHandler parameterHandler = mappedStatement.getLang().createParameterHandler(mappedStatement, parameterObject, boundSql);
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) 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) interceptorChain.pluginAll(statementHandler);
return statementHandler;
}
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) interceptorChain.pluginAll(executor);
return executor;
}
public Object pluginAll(Object target) {
for (Interceptor interceptor : interceptors) {
target = interceptor.plugin(target);
}
return target;
}
文档中拦截器的 plugin 方法实现是这样的 :
public Object plugin(Object target) {
return Plugin.wrap(target, this);
}
分析 org.apache.ibatis.plugin.Plugin 这个类 :
wrap 方法 : 如果传入的 interceptor 上有 @Intercepts , @Signature 注解 ,target 有接口 , 就为这个 target 生成一个代理对象 (使用的依旧是 jdk 的Proxy ), 否则返回原来的对象 。
public static Object wrap(Object target, Interceptor interceptor) {
Map<Class<?>, Set<Method>> signatureMap = getSignatureMap(interceptor);
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;
}
getSignatureMap 方法 : 作用就是获取到传入的拦截器类上注解 @Intercepts , @Signature 中指定拦截的对象类型和需要进行拦截的方法。@Signature 的三个属性 type , method , args 就可以定位一个方法了。
private static Map<Class<?>, Set<Method>> getSignatureMap(Interceptor interceptor) {
Intercepts interceptsAnnotation = interceptor.getClass().getAnnotation(Intercepts.class);
// issue #251
if (interceptsAnnotation == null) {
throw new PluginException("No @Intercepts annotation was found in interceptor " + interceptor.getClass().getName());
}
Signature[] sigs = interceptsAnnotation.value();
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 {
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);
}
}
return signatureMap;
}
getAllInterfaces 方法 : 获取指定 type 的所有接口类型 , 因为 jdk 的 Proxy 是基于接口的。
private static Class<?>[] getAllInterfaces(Class<?> type, Map<Class<?>, Set<Method>> signatureMap) {
Set<Class<?>> interfaces = new HashSet<Class<?>>();
while (type != null) {
for (Class<?> c : type.getInterfaces()) {
if (signatureMap.containsKey(c)) {
interfaces.add(c);
}
}
type = type.getSuperclass();
}
return interfaces.toArray(new Class<?>[interfaces.size()]);
}
org.apache.ibatis.plugin.Plugin 类是 java.lang.reflect.InvocationHandler 的实现类,这次 Plugin 在内部保存了被代理对象 target 。
invoke 方法 : 每次调用的方法如果是 @Signature 注解指定的方法 ,就去在调用目标方法前先去调用拦截器的 intercept 方法 。
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)) {
return interceptor.intercept(new Invocation(target, method, args));
}
return method.invoke(target, args);
} catch (Exception e) {
throw ExceptionUtil.unwrapThrowable(e);
}
}