Mybatis 拦截器执行原理分析

目录

1.拦截器执行流程

2.拦截器实现原理

3.拦截器用法


1.mybatis拦截器实现原理

Mybatis 拦截器执行原理分析_第1张图片

2.拦截器实现原理

在Mybaits中 拦截器需实现Interceptor接口,加上如下注解

@Intercepts({
  @Signature(type = StatementHandler.class, method = "prepare",
    args = { Connection.class, Integer.class})
})

表示代理对象是StatementHandler 代理的方法是prepare  只有执行prepare方法是 才会执行拦截器的拦截策略 ,mybatis是先加载所有的拦截器,然后在代理执行的时候 逐步遍历 责任链模式

拦截器的本质实现还是代理对象

  public static Object wrap(Object target, Interceptor interceptor) {
    Map, Set> 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;
  }

3.自己实现一个拦截器

@Intercepts({
  @Signature(type = StatementHandler.class, method = "prepare",
    args = { Connection.class, Integer.class})
})
public class LongYiLogPlugin implements Interceptor {

  private final  Logger log=LoggerFactory.getLogger(this.getClass());

  @Override
  public Object intercept(Invocation invocation) throws Throwable {
    StatementHandler statementHandler=(StatementHandler)invocation.getTarget();
    BoundSql boundSql=statementHandler.getBoundSql();
    String sql = boundSql.getSql();
    log.info("mclong intercept sql=>{}",sql);
    return invocation.proceed();
  }

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

  @Override
  public void setProperties(Properties properties) {
    String dialect =String.valueOf(properties.get("dialect")) ;
    log.info("mclongyi mybatis intercept dlatect {}",dialect);
  }
}

 

你可能感兴趣的:(Mybatis源码解析专栏,mybatis拦截器)