使用:https://www.yuque.com/wuxiangwuwo/dfvedv/rwu9u5
一 源码执行
1 Plugin类
import org.apache.ibatis.plugin.Plugin;/*主要为了把当前的拦截器生成代理存到拦截器链中*/@Overridepublic Object plugin(Object target) {Object wrap = Plugin.wrap(target, this);return wrap;}
Plugin实现了 InvocationHandler接口,因此它的invoke方法会拦截所有的方法调用。invoke方法会对所拦截的方法进行检测,以决定是否执行插件逻辑。该方法的逻辑如下:
@Overridepublic 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);}}/*** 创建目标类的代理对象** @param target 目标类* @param interceptor 拦截器对象* @return 代理对象*/public static Object wrap(Object target, Interceptor interceptor) {// 获得拦截的方法映射Map<Class<?>, Set<Method>> signatureMap = getSignatureMap(interceptor);// 获得目标类的类型Class<?> type = target.getClass();// 获得目标类的接口集合Class<?>[] interfaces = getAllInterfaces(type, signatureMap);// 若有接口,则创建目标对象的 JDK Proxy 对象if (interfaces.length > 0) {return Proxy.newProxyInstance(type.getClassLoader(),interfaces,new Plugin(target, interceptor, signatureMap));// 因为 Plugin 实现了 InvocationHandler 接口,所以可以作为 JDK 动态代理的调用处理器}// 如果没有,则返回原始的目标对象return target;}
invoke方法的代码比较少,逻辑不难理解。首先,invoke方法会检测被拦截方法是否配置在插件的@Signature注解中,若是,则执行插件逻辑,否则执行被拦截方法。插件逻辑封装在intercept方法中,该方法的参数类型为Invocationo。Invocation主要用于存储目标类,方法以及方法参数列表。
2 Invocation
下面简单看一下该类的定义
public class Invocation {/*** 目标对象*/private final Object target;/*** 方法对象*/private final Method method;/*** 方法参数数组*/private final Object[] args;// 省略有参构造和set/get方法/*** 调用方法** @return 调用结果*/public Object proceed() throws InvocationTargetException, IllegalAccessException {return method.invoke(target, args);}}
关于插件的执行逻辑就分析结束
