Mybatis源码 ------ plugin详解

本文深入解析了MyBatis中的拦截器配置,通过`<plugins>`标签设置拦截器,并展示了`pluginElement`方法如何处理`interceptor`属性和`property`标签。同时,详细介绍了代理对象的生成过程,如Executor、StatementHandler、ParameterHandler和ResultSetHandler的创建,以及`interceptorChain.pluginAll`方法如何为这些对象生成动态代理。最后,展示了Plugin类的`wrap`方法用于基于接口创建动态代理对象,以及`invoke`方法如何根据拦截器签名进行方法拦截。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  首先看到plugins标签的解析

    <plugins>
        <plugin interceptor="xxx.xx">
            <property name="x" value="x"/>
        </plugin>
    </plugins>
private void pluginElement(XNode parent) throws Exception {
    if (parent != null) {
      //获取子标签plugin
      for (XNode child : parent.getChildren()) {
        //获取interceptor属性值
        String interceptor = child.getStringAttribute("interceptor");
        //封装property标签的name value为Properties对象
        Properties properties = child.getChildrenAsProperties();
        //interceptor可以是别名的形式,获取到class对象
        //实例化Interceptor 
        Interceptor interceptorInstance = (Interceptor) resolveClass(interceptor).newInstance();
        //调用Interceptor的setProperties方法
        interceptorInstance.setProperties(properties);
        //将拦截器添加到configuration的interceptorChain中
        configuration.addInterceptor(interceptorInstance);
      }
    }
  }

  再来看代理对象的生成

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 = (Executor) interceptorChain.pluginAll(executor);
    return executor;
}
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 = (StatementHandler) interceptorChain.pluginAll(statementHandler);
    return statementHandler;
}
public ParameterHandler newParameterHandler(MappedStatement mappedStatement, Object parameterObject, BoundSql boundSql) {
    ParameterHandler parameterHandler = mappedStatement.getLang().createParameterHandler(mappedStatement, parameterObject, boundSql);
    //parameterHandler 可能生成代理对象
    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 = (ResultSetHandler) interceptorChain.pluginAll(resultSetHandler);
    return resultSetHandler;
}
public Object pluginAll(Object target) {
    //循环所有的interceptor 
    for (Interceptor interceptor : interceptors) {
      //接着看
      target = interceptor.plugin(target);
    }
    return target;
}
default Object plugin(Object target) {
    return Plugin.wrap(target, this);
}
public static Object wrap(Object target, Interceptor interceptor) {
    //获取类上的Intercepts注解信息
    Map<Class<?>, Set<Method>> signatureMap = getSignatureMap(interceptor);
    //被代理对象的类型
    Class<?> type = target.getClass();
    //while循环寻找被代理类和父类的接口类型,返回和注解配置的接口类型一致的
    Class<?>[] interfaces = getAllInterfaces(type, signatureMap);
    //有配置的接口类型被拦截
    if (interfaces.length > 0) {
      //基于接口生成动态代理对象
      return Proxy.newProxyInstance(
          type.getClassLoader(),
          interfaces,
          new Plugin(target, interceptor, signatureMap));
    }
    //不需要生成代理,直接返回原对象
    return target;
}
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());
    }
    //获取注解的value值
    Signature[] sigs = interceptsAnnotation.value();
    //建立接口类型和接口方法的映射关系
    Map<Class<?>, Set<Method>> signatureMap = new HashMap<>();
    //循环处理所有的Signature注解
    for (Signature sig : sigs) {
      //signatureMap是否有该接口类型,没有实例化一个HashSet
      Set<Method> methods = signatureMap.computeIfAbsent(sig.type(), k -> new HashSet<>());
      try {
        //获取到type下指定的方法,获取不到会抛异常
        Method method = sig.type().getMethod(sig.method(), sig.args());
        //添加到methods中
        methods.add(method);
      } catch (NoSuchMethodException e) {
        throw new PluginException("Could not find method on " + sig.type() + " named " + sig.method() + ". Cause: " + e, e);
      }
    }
    return signatureMap;
}
private static Class<?>[] getAllInterfaces(Class<?> type, Map<Class<?>, Set<Method>> signatureMap) {
    Set<Class<?>> interfaces = new HashSet<>();
    while (type != null) {
      //循环改类的所有的接口
      for (Class<?> c : type.getInterfaces()) {
        //如果signatureMap含有该接口类型
        if (signatureMap.containsKey(c)) {
          //加入到interfaces
          interfaces.add(c);
        }
      }
      //找父类
      type = type.getSuperclass();
    }
    //返回找到的接口类型
    return interfaces.toArray(new Class<?>[interfaces.size()]);
}
//再看到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)) {
        //执行intercept方法,入参包含为Invocation对象,target,method,args
        return interceptor.intercept(new Invocation(target, method, args));
      }
      //该方法不拦截,交由被代理对象自己调用
      return method.invoke(target, args);
    } catch (Exception e) {
      throw ExceptionUtil.unwrapThrowable(e);
    }
}
//Invocation对象含有proceed方法
public Object proceed() throws InvocationTargetException, IllegalAccessException {
    //被代理对象自己调用方法
    return method.invoke(target, args);
}

  plugin的源码还是比较简单的。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值