第一个拦截器

2019-05-11  本文已影响0人  忞触动心灵

拦截器类

package com.kaplan.interceptor;


import org.apache.ibatis.executor.resultset.ResultSetHandler;
import org.apache.ibatis.plugin.*;

import java.sql.Statement;
import java.util.Properties;


/*除了给拦截器实现拦截接口外(import org.apache.ibatis.plugin.Interceptor;) 还需要配置注解*/

/**
 * 插件签名
 * 告诉MyFistInterceptor(拦截器类)需要拦截哪个对象 的哪个方法
 */
@Intercepts({
        /*type就是设置需要拦截的哪个对象哪个接口*/
        @Signature(type = ResultSetHandler.class,/*mybatis四大对象*/
                method = "handleResultSets",/*对象的方法*/
                args= Statement.class)/*参数*/
})
public class MyFistInterceptor implements Interceptor {


    /*拦截目标对象的 目标方法*/
    public Object intercept(Invocation invocation) throws Throwable {
        /*invocation.getTarget() 获取目标对象*/
        System.out.println("拦截的目标对象:"+invocation.getTarget());

        /*执行目标对象的目标方法*/
        Object proceed = invocation.proceed();
        return proceed;
    }

    /*Object 参数就是这个拦截器需要拦截的对象 会在创建接口是实现类的时候调用它*/
    /*主要目的是包装目标对象 为目标对象创建动态代理对象*/
    public Object plugin(Object o) {
        System.out.println("将要包装的目标对象:"+o);

        /*将传入的当前类 创建代理对象*/
        return Plugin.wrap(o, this);
    }

    /*用来传递拦截器参数  获取配置文件中的属性*/
    public void setProperties(Properties properties) {

        System.out.println("插件配置的初始化参数: " + properties);
    }

}

Mybatis 核心配置

    <plugins>

        <!--interceptor 拦截器类全限定的名称(全类名)-->
        <plugin interceptor="com.kaplan.interceptor.MyFistInterceptor">

            <property name="hello" value="world"></property>

        </plugin>

    </plugins>
上一篇下一篇

猜你喜欢

热点阅读