MyBatis的插件开发可参考:MyBatis简单分页插件实现
插件实现通过实现MyBatis提供的Interceptor接口
public interface Interceptor {
//拦截执行
Object intercept(Invocation invocation) throws Throwable;
//对对象进行增强
Object plugin(Object target);
//属性设置,MyBatis在读取配置文件的时候会调用
void setProperties(Properties properties);
}
plugin方法里决定要不要对对象进行增强,它在Configuration类中的下面几个方法中被调用,所以Mybatis可以对Excutor、ParameterHandler、ResultSetHandler、StatementHandler进行插件开发。
通常plugin方法的实现用MyBatis提供的Plugin类进行处理
public Object plugin(Object target) {
return Plugin.wrap(target, this);
}
public static Object wrap(Object target, Interceptor interceptor) {
//1.拿到@Intercepts、@Signature注解的相关信息
Map<Class<?>, Set<Method>> signatureMap = getSignatureMap(interceptor);
Class<?> type = target.getClass();
//2.根据传进来的对象类型查找匹配的接口
Class<?>[] interfaces = getAllInterfaces(type, signatureMap);
if (interfaces.length > 0) {//数量不为0,说明需要拦截
//3.进行JDK动态代理
return Proxy.newProxyInstance(
type.getClassLoader(),
interfaces,
new Plugin(target, interceptor, signatureMap));
}
//不需要代理
return target;
}
1.拿到@Intercepts、@Signature注解的相关信息
例子:
@Intercepts(
@Signature(type = Executor.class,
method = "query",
args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class})
)
private static Map<Class<?>, Set<Method>> getSignatureMap(Interceptor interceptor) {
//拿到Intercepts注解
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注解
Signature[] sigs = interceptsAnnotation.value();
//用于保存结果,键为要拦截的类,值为拦截类中的目标方法的Set集合
Map<Class<?>, Set<Method>> signatureMap = new HashMap<Class<?>, Set<Method>>();
for (Signature sig : sigs) {
Set<Method> methods = signatureMap.get(sig.type());
if (methods == null) {//第一次就创建一个HashSet
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;
}
2.根据传进来的对象类型查找匹配的接口
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()]);
}
3.进行JDK动态代理
return Proxy.newProxyInstance(
type.getClassLoader(),
interfaces,
new Plugin(target, interceptor, signatureMap));
这里看到代理实现类就是Plugin(public class Plugin implements InvocationHandler),所以拦截的主要逻辑在Plugin类的invoke方法
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)) {
//如果拦截方法中存在当前正要执行的方法method,就调用插件的intercept方法
return interceptor.intercept(new Invocation(target, method, args));
}
//否则直接执行返回
return method.invoke(target, args);
} catch (Exception e) {
throw ExceptionUtil.unwrapThrowable(e);
}
}
上面逻辑很简单,就是判断当前要执行的方法是否要拦截,拦截就执行插件的intercept方法,否则就直接执行返回。
最后PS:插件Interceptor接口的setProperties方法在XMLConfigBuilder类中的pluginElement方法中进行调用。
private void pluginElement(XNode parent) throws Exception {
if (parent != null) {
//遍历MyBatis的XML配置中的插件配置节点
for (XNode child : parent.getChildren()) {
String interceptor = child.getStringAttribute("interceptor");
Properties properties = child.getChildrenAsProperties();
//实例化插件
Interceptor interceptorInstance = (Interceptor) resolveClass(interceptor).newInstance();
//调用插件的setProperties方法
interceptorInstance.setProperties(properties);
//把插件实例加入configuration的插件缓存中
configuration.addInterceptor(interceptorInstance);
}
}
}