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);
}
}
}