Mybatis之Plugin使用及原理

近期一个业务需要配置禁写,想通过Mybatis的Plugin来做,于是有了这篇文章。先来看官网对Plugin的介绍(以下内容来自官网)

// MyBatis 允许你在映射语句执行过程中的某一点进行拦截调用。默认情况下,MyBatis 允许使用插件来拦截的方法调用包括:

Executor (update, query, flushStatements, commit, rollback, getTransaction, close, isClosed)
ParameterHandler (getParameterObject, setParameters)
ResultSetHandler (handleResultSets, handleOutputParameters)
StatementHandler (prepare, parameterize, batch, update, query)

也就是说,在mybatis的执行流程中,支持Plugin的场景有且仅有:Executor、ParameterHandler、StatementHandler以及ResultSetHandler。针对我们的需求,刚开始打算直接从Executor入手,实现禁写并保存sql,下面是处理类

@Intercepts({
            // 注意,这里的type只能是接口,否则不会生效,具体原因参考下面的源码
        @Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class})
})
public class ForbidInterceptor implements Interceptor {

    private Properties properties;
    private static final Logger LOGGER = LoggerFactory.getLogger(ForbidInterceptor.class);
    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        Executor executor = (Executor)invocation.getTarget();
        MappedStatement statement = (MappedStatement)invocation.getArgs()[0];
        Object paramObject = invocation.getArgs()[1];
        Configuration configuration = statement.getConfiguration();
        StatementHandler handler = configuration.newStatementHandler(executor, statement, paramObject, RowBounds.DEFAULT, null, null);
      
        // 简单期间,拿到PreparedStatement,有点多此一举,不如直接切PreparedStatmentHandler
        PreparedStatement preparedStatement = (PreparedStatement) prepareStatement(handler,executor.getTransaction().getConnection(),executor.getTransaction());
        String rawSql = preparedStatement.toString();
        int updateIndex = rawSql.indexOf("update") == -1 ? rawSql.indexOf("insert") : -1;
        if(updateIndex == -1 ){
            return invocation.proceed();
        }
      
        //业务逻辑省略,这里仅打印执行sql,然后直接返回1,并不会真实执行sql  
        rawSql = rawSql.substring(updateIndex);
        LOGGER.info("row sql : " + rawSql);
        return (Object)1;
    }
    
    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target,this);
    }

    @Override
    public void setProperties(Properties properties) {
        this.properties = properties;
    }
        
    // 这里参照mybatis对preparedStatement的处理
    private Statement prepareStatement(StatementHandler handler, Connection connection, Transaction transaction) throws SQLException {
        Statement stmt;
        stmt = handler.prepare(connection, transaction.getTimeout());
        handler.parameterize(stmt);
        return stmt;
    }

虽然可以实现禁写的目的,但是就像代码中注释的那样,有点多此一举;所以,直接来切PreparedStatementHandler,下面是处理类

@Intercepts({
        @Signature(type = StatementHandler.class, method = "update", args = {Statement.class})
})
public class ForbidInterceptorForMmc implements Interceptor {

    private Properties properties;
    private static final Logger LOGGER = LoggerFactory.getLogger(ForbidInterceptor.class);

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        PreparedStatement ps = (PreparedStatement)invocation.getArgs()[0];
        if(Objects.nonNull(ps)){
            // 省略业务逻辑,仅打印sql
            String rawSql = ps.toString();
            int updateIndex = rawSql.indexOf("update") == -1 ? rawSql.indexOf("insert") : -1;
            // 非更新语句,直接执行
            if(updateIndex == -1 ){
                return invocation.proceed();
            }
            rawSql = rawSql.substring(updateIndex);
            LOGGER.info("row sql : " + rawSql);
        }
        return 1;
    }

    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target,this);
    }

    @Override
    public void setProperties(Properties properties) {
        this.properties = properties;
    }

结果也比较简单,可以看到具体待执行的sql(实际业务场景可能需要保存sql):

c.s.i.t.interceptor.ForbidInterceptor    : row sql : 
insert into employees (birth_date, first_name, last_name,gender, hire_date)
                    values ('2021-06-01 17:08:58', 'zhang', 'san',1, '2021-06-01 17:08:58')

基本功能实现了,来都来了,顺道看看Plugin的实现吧。

Mybatis中Plugin流程主要包括Plugin、Interceptor、InterceptorChain三个核心类;其中Interceptor定义插件实际逻辑,然后Plugin使用JDK的动态代理对targetObject进行代理(通常是Executor、PremeterHandler、StatementHandler、ResultSetHandler的实现),最后在调用被代理对象方法时调用invoke(),执行Interceptor逻辑,所以可以把Plugin看作是wrapper+proxy。InterceptorChain负责Interceptor的管理。使用Plugin通常需要实现org.apache.ibatis.plugin.Interceptor,并重写intercept()和plugin() (通常是Plugin.wrap(targe,this))。整个Plugin的执行周期主要包括装配和执行两部分,如下图所示:

mybatis-plugin.jpg

先来看Plugin的装配,可以分为两步:将Interceptor加入InterceptorChain、对targetObject进行代理。InterceptorChain负责装配Plugin,装配的总入口在Configuration,先来看第一步

public class InterceptorChain {
    // 全局Plugin
  private final List<Interceptor> interceptors = new ArrayList<Interceptor>();
    
  // 组装所有plugin,最终结果是target的代理
  public Object pluginAll(Object target) {
    for (Interceptor interceptor : interceptors) {
      // 核心,为target生成proxy,同时封装interceptor执行逻辑
      target = interceptor.plugin(target);
    }
    return target;
  }
    
  // 添加Interceptor
  public void addInterceptor(Interceptor interceptor) {
    interceptors.add(interceptor);
  }
  
  public List<Interceptor> getInterceptors() {
    return Collections.unmodifiableList(interceptors);
  }

XMLConfigBuilder(解析mybatis-config.xml)和Configuration都有Plugin装配的入口,XMLConfigBuilder最终也是通过Configuration实现。先来看XMLConfigBuilder

private void pluginElement(XNode parent) throws Exception {
  if (parent != null) {
    for (XNode child : parent.getChildren()) {
      String interceptor = child.getStringAttribute("interceptor");
      Properties properties = child.getChildrenAsProperties();
      Interceptor interceptorInstance = (Interceptor) resolveClass(interceptor).newInstance();
      interceptorInstance.setProperties(properties);
      // 借助configuration实现plugin装配
      configuration.addInterceptor(interceptorInstance);
    }
  }
}
public void addInterceptor(Interceptor interceptor) {
    interceptorChain.addInterceptor(interceptor);
}

下面这段Configuration中的逻辑可以解释官网中对拦截点的说明(仅支持ParameterHandler、ResultSetHandler、StatementHandler、Executor

// 创建ParameterHandler时,为ParameterHandler装配Plugins
public ParameterHandler newParameterHandler(MappedStatement mappedStatement, Object parameterObject, BoundSql boundSql) {
    ParameterHandler parameterHandler = mappedStatement.getLang().createParameterHandler(mappedStatement,                   parameterObject, boundSql);
    // 为ParameterHandler装配Plugins
    parameterHandler = (ParameterHandler) interceptorChain.pluginAll(parameterHandler);
    return parameterHandler;
}

// 创建ResultSetHandler时,为ResultSetHandler装配Plugins
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装配Plugins
    resultSetHandler = (ResultSetHandler) interceptorChain.pluginAll(resultSetHandler);
    return resultSetHandler;
}

// 创建StatementHandler时,为StatementHandler装配Plugins
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装配Plugins
    statementHandler = (StatementHandler) interceptorChain.pluginAll(statementHandler);
    return statementHandler;
}

// 创建Executor时,为Executor装配Plugins
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装配Plugins
    executor = (Executor) interceptorChain.pluginAll(executor);
    return executor;
  }

此时所有Interceptor已经全部加入到InterceptorChain,接着,对targetObject进行层层代理,核心逻辑如下:

public Object pluginAll(Object target) {
    for (Interceptor interceptor : interceptors) {
      // 核心,为target生成proxy,同时封装interceptor执行逻辑
      target = interceptor.plugin(target);
    }
    return target;
}

// 下面是Plugin类的核心逻辑
public static Object wrap(Object target, Interceptor interceptor) {
    // @Intercepts注解处理
    Map<Class<?>, Set<Method>> signatureMap = getSignatureMap(interceptor);
    // 被代理类真实类型
    Class<?> type = target.getClass();
    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 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注解内容至signatureMap,格式为<Class(拦截的接口),Set<Method>(拦截的接口方法集合)>,
    Signature[] sigs = interceptsAnnotation.value();
    Map<Class<?>, Set<Method>> signatureMap = new HashMap<Class<?>, Set<Method>>();
    for (Signature sig : sigs) {
      Set<Method> methods = signatureMap.get(sig.type());
      if (methods == null) {
        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;
}

// 过滤被代理类需要被代理的接口
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()) {
        // 接口在signatureMap,则会生成代理类
        if (signatureMap.containsKey(c)) {
          interfaces.add(c);
        }
      }
      type = type.getSuperclass();
    }
    return interfaces.toArray(new Class<?>[interfaces.size()]);
}

Plugin的执行相对比较简单,因为Plugin实现了JDK的InvocationHandler接口(invoke方法),调用被代理类对象方法,会执行Plugin的invoke(),逻辑如下;

@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
  try {
    Set<Method> methods = signatureMap.get(method.getDeclaringClass());
    // 当前方法在被代理方法集合内,执行intercept逻辑
    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);
  }
}

这就是Mybatis中对Plugin的实现,核心是通过JDK的动态代理对target进行代理,并利用责任链模式对Plugin进行装配。最后,欢迎指正。

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 219,539评论 6 508
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,594评论 3 396
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 165,871评论 0 356
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,963评论 1 295
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,984评论 6 393
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,763评论 1 307
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,468评论 3 420
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,357评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,850评论 1 317
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 38,002评论 3 338
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,144评论 1 351
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,823评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,483评论 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,026评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,150评论 1 272
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,415评论 3 373
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,092评论 2 355

推荐阅读更多精彩内容