Mybatis拦截器执行顺序

Mybatis interceptor execution order

我在mybatis-config.xml.

中定义了两个拦截器
<plugins>
    <plugin interceptor="cn.common.interceptor.DbInterceptor"/>
    <plugin interceptor="cn.common.interceptor.MybatisInterceptor"/>
</plugins>

两个拦截器的实现。

@Intercepts(value = {
        @Signature (type=Executor.class, method="update", args = { MappedStatement.class, Object.class })})
public class DbInterceptor implements Interceptor {

    private Properties properties;

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        System.out.println("db interceptor invoke");
        return invocation.proceed();
    }

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

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


@Intercepts({
        @Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class})})
public class MybatisInterceptor implements Interceptor {

    private Properties properties;

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        System.out.println("mybatis interceptor invoke");
        return invocation.proceed();
    }

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

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

}

MybatisInterceptor是我执行update方法后第一次执行

但是我想让DbInterceptor拦截器先执行,怎么办?

MyBatis中,后一个插件会先执行,所以我认为你只需要更改插件的配置顺序即可:

变化自

<plugins>
    <plugin interceptor="cn.common.interceptor.DbInterceptor"/>
    <plugin interceptor="cn.common.interceptor.MybatisInterceptor"/>
</plugins>

<plugins>
    <plugin interceptor="cn.common.interceptor.MybatisInterceptor"/>
    <plugin interceptor="cn.common.interceptor.DbInterceptor"/>
</plugins>

可以在 CSDN

找到更多详细信息