(基于spring-mybatis)运行自定义的插件,需要3 步,我们以PageHelper 为
1、编写自己的插件类
1)实现Interceptor 接口
这个是所有的插件必须实现的接口。
2)添加@Intercepts({@Signature()}),指定拦截的对象和方法、方法参数方法名称+参数类型,构成了方法的签名,决定了能够拦截到哪个方法。
问题:拦截签名跟参数的顺序有关系吗?
3)实现接口的3 个方法
// 用于覆盖被拦截对象的原有方法(在调用代理对象Plugin 的invoke()方法时被调用)
Object intercept(Invocation invocation) throws Throwable;
// target 是被拦截对象,这个方法的作用是给被拦截对象生成一个代理对象,并返回它
Object plugin(Object target);
// 设置参数
void setProperties(Properties properties);
2、插件注册,在mybatis-config.xml 中注册插
<plugins>
<plugin interceptor="com.github.pagehelper.PageInterceptor">
<property name="offsetAsPageNum" value="true"/>
……后面全部省略……
</plugin>
</plugins>
3、插件登记
MyBatis 启动时扫描<plugins> 标签, 注册到Configuration 对象的InterceptorChain 中。property 里面的参数,会调用setProperties()方法处理。
以上就是编写和使用自定义插件的全部步骤。