使用:https://www.yuque.com/wuxiangwuwo/dfvedv/rwu9u5

一 源码执行

1 Plugin类

  1. import org.apache.ibatis.plugin.Plugin;
  2. /*
  3. 主要为了把当前的拦截器生成代理存到拦截器链中
  4. */
  5. @Override
  6. public Object plugin(Object target) {
  7. Object wrap = Plugin.wrap(target, this);
  8. return wrap;
  9. }

Plugin实现了 InvocationHandler接口,因此它的invoke方法会拦截所有的方法调用。invoke方法会对所拦截的方法进行检测,以决定是否执行插件逻辑。该方法的逻辑如下:

  1. @Override
  2. public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
  3. try {
  4. // 获得目标方法是否被拦截
  5. Set<Method> methods = signatureMap.get(method.getDeclaringClass());
  6. if (methods != null && methods.contains(method)) {
  7. // 如果是,则拦截处理该方法
  8. return interceptor.intercept(new Invocation(target, method, args));
  9. }
  10. // 如果不是,则调用原方法
  11. return method.invoke(target, args);
  12. } catch (Exception e) {
  13. throw ExceptionUtil.unwrapThrowable(e);
  14. }
  15. }
  16. /**
  17. * 创建目标类的代理对象
  18. *
  19. * @param target 目标类
  20. * @param interceptor 拦截器对象
  21. * @return 代理对象
  22. */
  23. public static Object wrap(Object target, Interceptor interceptor) {
  24. // 获得拦截的方法映射
  25. Map<Class<?>, Set<Method>> signatureMap = getSignatureMap(interceptor);
  26. // 获得目标类的类型
  27. Class<?> type = target.getClass();
  28. // 获得目标类的接口集合
  29. Class<?>[] interfaces = getAllInterfaces(type, signatureMap);
  30. // 若有接口,则创建目标对象的 JDK Proxy 对象
  31. if (interfaces.length > 0) {
  32. return Proxy.newProxyInstance(
  33. type.getClassLoader(),
  34. interfaces,
  35. new Plugin(target, interceptor, signatureMap));
  36. // 因为 Plugin 实现了 InvocationHandler 接口,所以可以作为 JDK 动态代理的调用处理器
  37. }
  38. // 如果没有,则返回原始的目标对象
  39. return target;
  40. }

invoke方法的代码比较少,逻辑不难理解。首先,invoke方法会检测被拦截方法是否配置在插件的@Signature注解中,若是,则执行插件逻辑,否则执行被拦截方法。插件逻辑封装在intercept方法中,该方法的参数类型为Invocationo。Invocation主要用于存储目标类,方法以及方法参数列表。

2 Invocation

下面简单看一下该类的定义

  1. public class Invocation {
  2. /**
  3. * 目标对象
  4. */
  5. private final Object target;
  6. /**
  7. * 方法对象
  8. */
  9. private final Method method;
  10. /**
  11. * 方法参数数组
  12. */
  13. private final Object[] args;
  14. // 省略有参构造和set/get方法
  15. /**
  16. * 调用方法
  17. *
  18. * @return 调用结果
  19. */
  20. public Object proceed() throws InvocationTargetException, IllegalAccessException {
  21. return method.invoke(target, args);
  22. }
  23. }

关于插件的执行逻辑就分析结束