mybatis多个plugins的执行顺序

一、前言

   在mybatis官网中,有插件一说  mybatis plugins . 如果同时有多个插件,那么他们的执行顺序是怎样的?

 

二、准备工作、代码准备

1、 项目结构

2、TestDAO

public interface TestDAO {
    Test selectById(Integer id);

    default void testDefaultMethod(){
        System.out.println("===调用接口中的默认方法,用来验证MapperProxy中的isDefaultMethod方法===");
    }
}

3、Test

@Data
@NoArgsConstructor
@AllArgsConstructor
public class Test {
    private Integer id;

    private String name;
}

4、ExamplePlugin

@Intercepts({@Signature(
        type= Executor.class, method = "query", args={MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class}
        ),
        @Signature(
                type = ParameterHandler.class, method = "setParameters", args = {PreparedStatement.class}
        ),
        @Signature(
                type = ResultSetHandler.class, method = "handleResultSets", args = {Statement.class}
        ),
        @Signature(
                type = StatementHandler.class, method = "prepare", args = {Connection.class, Integer.class}
        )
})
public class ExamplePlugin implements Interceptor {
    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        System.out.println("==== ExamplePlugin 开始搞事情:" + invocation.getMethod().getName() + "  ====");
        return invocation.proceed();
    }

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

    @Override
    public void setProperties(Properties properties) {

    }
}

5、SecondExamplePlugin

@Intercepts({@Signature(
        type= Executor.class, method = "query", args={MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class}
        ),
        @Signature(
                type = ParameterHandler.class, method = "setParameters", args = {PreparedStatement.class}
        ),
        @Signature(
                type = ResultSetHandler.class, method = "handleResultSets", args = {Statement.class}
        ),
        @Signature(
                type = StatementHandler.class, method = "prepare", args = {Connection.class, Integer.class}
        )
})
public class SecondExamplePlugin implements Interceptor {
    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        System.out.println("==== SecondExamplePlugin 开始搞事情:" + invocation.getMethod().getName() + "  ====");
        return invocation.proceed();
    }

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

    @Override
    public void setProperties(Properties properties) {

    }
}

6、Main

public class Main {

    public static SqlSession getSqlSession() throws IOException {
        InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        return sqlSessionFactory.openSession();
    }

    public static void main(String[] args) throws IOException {
        TestDAO testDAO = getSqlSession().getMapper(TestDAO.class);
        Test test = testDAO.selectById(1);

//        testDAO.testDefaultMethod();

        //类文件是缓存在java虚拟机中,我们将类文件打印到文件中,便于查看
//        generateProxyFile("F:/TestDAOProxy.class");
    }

    private static void generateProxyFile(String path){
        byte[] classFile = ProxyGenerator.generateProxyClass("$Proxy0", new Class<?>[]{TestDAO.class});

        try(FileOutputStream fos = new FileOutputStream(path)) {
            fos.write(classFile);
            fos.flush();
            System.out.println("代理类class文件写入成功");
        } catch (Exception e) {
            System.out.println("写文件错误");
        }
    }
}

7、 TestMapper.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="com.me.mybatis.dao.TestDAO">
    <resultMap id="testMap" type="com.me.mybatis.domain.Test">
        <result property="id" column="id" />
        <result property="name" column="name" />
    </resultMap>

    <sql id="allColumn">
        id, name
    </sql>

    <select id="selectById" resultMap="testMap">
        SELECT <include refid="allColumn"/>
        FROM test
        WHERE id = #{id}
    </select>

</mapper>

8、mybatis-confi.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <plugins>
        <plugin interceptor="com.me.mybatis.plugin.ExamplePlugin">
            <property name="someProperty" value="200" />
        </plugin>
        <plugin interceptor="com.me.mybatis.plugin.SecondExamplePlugin">
            <property name="someProperty" value="200" />
        </plugin>
    </plugins>

    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/mybatis_test?useUnicode=true&amp;characterEncoding=utf-8&amp;useSSL=false&amp;useJDBCCompliantTimezoneShift=true&amp;useLegacyDatetimeCode=false&amp;serverTimezone=UTC"/>
                <property name="username" value="root"/>
                <property name="password" value="NewPwd@123"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="mappers/TestMapper.xml"/>
    </mappers>
</configuration>

9、POM

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.me</groupId>
    <artifactId>mybatis-test</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.6</version>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.16.14</version>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.12</version>
        </dependency>
    </dependencies>

</project>

 

三、开始探索

1、运行结果

==== SecondExamplePlugin 开始搞事情:query  ====
==== ExamplePlugin 开始搞事情:query  ====
==== SecondExamplePlugin 开始搞事情:prepare  ====
==== ExamplePlugin 开始搞事情:prepare  ====
==== SecondExamplePlugin 开始搞事情:setParameters  ====
==== ExamplePlugin 开始搞事情:setParameters  ====
==== SecondExamplePlugin 开始搞事情:handleResultSets  ====
==== ExamplePlugin 开始搞事情:handleResultSets  ====

 

2、疑问:为什么是这样的顺序?

和我们在mybatis-config.xml文件中的顺序相反,为什么?

 

3、注释掉一个,我们从一个plugin开始debug,看看做了什么

 

4、如图,在Configuration的四个方法newParameterHandler、newResultSetHandler、newStatementHandler、newExecutor中打上断点

 

5、debug  Main类的main方法

 

6、我们发现在newExecutor中,被拦住了

    这里的interceptorChain是什么东西?我们往上找一找,发现它是在Configuration类中new出来的。它等价于mybatis-config中的<plugins></plugins>

 

7、我们已经知道interceptorChain是什么了,那么进入它的pluginAll方法

   我们可以看到它是遍历interceptors的plugin方法。而interceptors是ArrayList,是有序的。那么在配置文件中,哪个plugin在前,这里它就在前面

 

8、进入interceptor的plugin方法,发现我们来到了我们自己写的ExamplePlugin类的plugin方法

 

9、它又继续调用了Plugin的静态方法wrap

  1)  第一步获取@Signature注解中的type和method,也就是我们在ExamplePlugin中使用的注解。

   

2)第二步,用动态代理,生成代理类。其中Plugin作为InvocationHandler

 

10、UML图

  最终Executor不再是原来的类,而是它的代理类。newStatementHandler方法和newResultSetHandler方法的流程,也差不多,最终也是生成代理类。

 

当Executor、StatementHandler、ParameterHandler、ResultSetHandler执行他们自己的方法时,实际上调用他们的代理类Plugin中的invoke方法。

也就是在interceptor.intercept(new Invocation(target, method, args));这一句中,回到了我们ExamplePlugin的intercept方法

整个流程中Executor的代理。(这里只拿Executor来举例)

 

四、结论

  上面只是代理一次,还记得pluginAll吗?

多个interceptor呢?当然是代理类又被代理了

所以,后面的将会代理前面的,这也就是为什么SecondExamplePlugin先执行的原因了——越外层的越先执行嘛

 

   多个插件的执行顺序已经明了了,那么插件里面方法的执行顺序呢?

当然是看这些方法什么时候被调用咯

  • 12
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 5
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值