简述Mybatis的插件运行原理,以及如何编写一个插件?

插件原理:在四大对象创建的时候
 1、每个创建出来的对象不是直接返回的,而是
      interceptorChain.pluginAll(parameterHandler);
 2、获取到所有的Interceptor(拦截器)(插件需要实现的接口);
      调用interceptor.plugin(target);返回target包装后的对象
 3、插件机制,我们可以使用插件为目标对象创建一个代理对象;AOP(面向切面)
       我们的插件可以为四大对象创建出代理对象;
       代理对象就可以拦截到四大对象的每一个执行;

编写插件

1、创建插件类实现interceptor接口并且使用注解标注拦截对象与方法

package city.albert;

/**
 * @author niunafei
 * @function
 * @email [email protected]
 * @date 2020/6/11  6:08 PM
 */

import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;

import java.lang.reflect.Method;
import java.util.Properties;

/**
 * 注解声明mybatis当前插件拦截哪个对象的哪个方法
 * <p>
 * type表示要拦截的目标对象 Executor.class StatementHandler.class  ParameterHandler.class ResultSetHandler.class
 * method表示要拦截的方法,
 * args表示要拦截方法的参数
 *
 * @author niuanfei
 */
@Intercepts({
        @Signature(type = Executor.class, method = "query",
                args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class})})
public class TestInterceptor implements Interceptor {

    /**
     * 拦截目标对象的目标方法执行
     *
     * @param invocation
     * @return
     * @throws Throwable
     */
    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        //被代理对象
        Object target = invocation.getTarget();
        //代理方法
        Method method = invocation.getMethod();
        //方法参数
        Object[] args = invocation.getArgs();
        // do something ...... 方法拦截前执行代码块
        //执行原来方法
        Object result = invocation.proceed();
        // do something .......方法拦截后执行代码块
        return result;
    }

    /**
     * 包装目标对象:为目标对象创建代理对象
     *
     * @param target
     * @return
     */
    @Override
    public Object plugin(Object target) {
        System.out.println("MySecondPlugin为目标对象" + target + "创建代理对象");
        //this表示当前拦截器,target表示目标对象,wrap方法利用mybatis封装的方法为目标对象创建代理对象(没有拦截的对象会直接返回,不会创建代理对象)
        Object wrap = Plugin.wrap(target, this);
        return wrap;
    }

    /**
     * 设置插件在配置文件中配置的参数值
     *
     * @param properties
     */
    @Override
    public void setProperties(Properties properties) {
        System.out.println(properties);
    }
}

2、在配置文件中写入plugins标签

 <plugins>
        <plugin interceptor="city.albert.TestInterceptor">
            <property name="name" value="name"/>
        </plugin>
    </plugins>

注:此文章为个人汇总笔记,原文链接为——https://www.cnblogs.com/niunafei/p/13096782.html

猜你喜欢

转载自blog.csdn.net/weixin_42495773/article/details/106799310
今日推荐