首页 技术 正文
技术 2022年11月7日
0 收藏 359 点赞 1,070 浏览 10487 个字

详解Mybatis拦截器(从使用到源码)

MyBatis提供了一种插件(plugin)的功能,虽然叫做插件,但其实这是拦截器功能。

本文从配置到源码进行分析.

一、拦截器介绍

MyBatis 允许你在已映射语句执行过程中的某一点进行拦截调用。默认情况下,MyBatis 允许使用插件来拦截的方法调用包括:

  1. Executor (update, query, flushStatements, commit, rollback, getTransaction, close, isClosed)
  2. ParameterHandler (getParameterObject, setParameters)
  3. ResultSetHandler (handleResultSets, handleOutputParameters)
  4. StatementHandler (prepare, parameterize, batch, update, query)

概括一下,分别是拦截执行器、参数控制器、结果控制器、SQL语句构建控制器,对执行流程进行更改.对应四个对象:

二、拦截器图示

三、拦截器使用

1、测试类

    @Test
public void testQueryByNo() throws IOException {
Reader reader =
Resources.getResourceAsReader("mybatis-config.xml");
SqlSessionFactory sessionFactory
= new SqlSessionFactoryBuilder().build(reader);
SqlSession session = sessionFactory.openSession();
//传入StudentMapper接口,返回该接口的mapper代理对象studentMapper
StudentMapper studentMapper = session.getMapper(StudentMapper.class);//接口
//通过mapper代理对象studentMapper,来调用IStudentMapper接口中的方法
Student student = studentMapper.queryStudentByNo(1);
System.out.println(student);
session.close();
}

2、实现接口

自定义类实现Interceptor接口

public class MyInterceptor implements Interceptor {
public Object intercept(Invocation invocation) throws Throwable {
//放行方法
Object proceed = invocation.proceed();
return proceed;
}
public Object plugin(Object target) {
Object wrap = Plugin.wrap(target, this);
return wrap;
}
public void setProperties(Properties properties) {
}
}
类中方法解释:

intercept :起拦截作用,在此定义一些功能

plugin :将需要增强的方法以及拦截器中增强的部分整合再返回,这个方法会执行四次,对四个处理器都会增

​强,第一次执行是在sessionFactory.openSession()之后,由源码可以知道四个默认拦截器是:

>>>CachingExecutor
>>>
>>>DefaultParameterHandler
>>>
>>>DefaultResultSetHandler
>>>
>>>RoutingStatementHandler

setProperties :设置变量属性,这个方法在SqlSessionFactoryBuilder().build(reader)之后执行

3、添加注解

在上面的实现类上添加注解

@Intercepts({
@Signature(
type = StatementHandler.class,
method = "query",
args = {Statement.class, ResultHandler.class}
)})

signature参数解释:

​ type : 这儿主要是拦截对象的类型,是前面拦截器介绍中的四种之一,或多种(源码中type返回值是数组)

method : 方法只能是一个值,

​ args: 值是前面介绍的四种拦截器括号中的内容,可以有多个.

4、配置文件

修改mybatis-config.xml文件

位置:typeAliases之后,environments之前(如果不记得,可以故意输错,然后idea会提示)

    <plugins>
<plugin interceptor="com.courage.mybatis.my.interceptors.MyInterceptor">
<property name="name" value="zs"/>
<property name="age" value="23"/>
</plugin>
</plugins>

四、多个拦截器执行顺序

如果有多个拦截器,拦截顺序会按照mybatis-config.xml中plugins标签里面拦截器先后顺序,但是调用执行的顺序相反

五、拦截器拦截后进行修改

    public Object intercept(Invocation invocation) throws Throwable {
Object target = invocation.getTarget();
MetaObject metaObject = SystemMetaObject.forObject(target);
Object value = metaObject.getValue("parameterHandler.parameterObject");
metaObject.setValue("parameterHandler.parameterObject",2);
Object proceed = invocation.proceed();
return proceed;
}

要点:

metaObject.getValue()方法是参数值,可以通过打印上一步的target,获取对象(类)源码,查看类中包含的value

在本文分析的RoutingStatementHandler中,有两个可以get的值(get表示有这个属性),而 metaObject.setValue(“parameterHandler.parameterObject”,2);中的parameterHandler就是默认的DefaultParameterHandler,可以通过打印拦截器里面的plugin方法里面的wrap得知:

org.apache.ibatis.executor.CachingExecutor@bcef303

org.apache.ibatis.scripting.defaults.DefaultParameterHandler@2f1de2d6

org.apache.ibatis.executor.resultset.DefaultResultSetHandler@289710d9

org.apache.ibatis.executor.statement.RoutingStatementHandler@5143c662

对得到的参数对象重新进行赋值为2(原来为1)查询,结果:

学号:2姓名:lixiaosi年龄:30年级:middle

六、源码分析

首先从源头->配置文件开始分析:

1、pluginElement方法

XMLConfigBuilder解析MyBatis全局配置文件的pluginElement私有方法:

private void pluginElement(XNode parent) throws Exception {
if (parent != null) {
for (XNode child : parent.getChildren()) {
String interceptor = child.getStringAttribute("interceptor");
Properties properties = child.getChildrenAsProperties();
Interceptor interceptorInstance = (Interceptor) resolveClass(interceptor).newInstance();
interceptorInstance.setProperties(properties);
configuration.addInterceptor(interceptorInstance);
}
}
}

具体的解析代码其实比较简单,就不贴了,主要就是通过反射实例化plugin节点中的interceptor属性表示的类。然后调用全局配置类Configuration的addInterceptor方法。

public void addInterceptor(Interceptor interceptor) {
interceptorChain.addInterceptor(interceptor);
}

2、InterceptorChain类

这个interceptorChain是Configuration的内部属性,类型为InterceptorChain,也就是一个拦截器链,我们来看下它的定义:

public class InterceptorChain {  private final List<Interceptor> interceptors = new ArrayList<Interceptor>();  public Object pluginAll(Object target) {
for (Interceptor interceptor : interceptors) {
target = interceptor.plugin(target);
}
return target;
} public void addInterceptor(Interceptor interceptor) {
interceptors.add(interceptor);
} public List<Interceptor> getInterceptors() {
return Collections.unmodifiableList(interceptors);
}}

3、为何拦截器会拦截几个处理器?

现在我们理解了拦截器配置的解析以及拦截器的归属,现在我们回过头看下为何拦截器会拦截这些方法(Executor,ParameterHandler,ResultSetHandler,StatementHandler的部分方法):

public ParameterHandler newParameterHandler(MappedStatement mappedStatement, Object parameterObject, BoundSql boundSql) {
ParameterHandler parameterHandler = mappedStatement.getLang().createParameterHandler(mappedStatement, parameterObject, boundSql);
parameterHandler = (ParameterHandler) interceptorChain.pluginAll(parameterHandler);
return parameterHandler;
}public ResultSetHandler newResultSetHandler(Executor executor, MappedStatement mappedStatement, RowBounds rowBounds, ParameterHandler parameterHandler,
ResultHandler resultHandler, BoundSql boundSql) {
ResultSetHandler resultSetHandler = new DefaultResultSetHandler(executor, mappedStatement, parameterHandler, resultHandler, boundSql, rowBounds);
resultSetHandler = (ResultSetHandler) interceptorChain.pluginAll(resultSetHandler);
return resultSetHandler;
}public StatementHandler newStatementHandler(Executor executor, MappedStatement mappedStatement, Object parameterObject, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) {
StatementHandler statementHandler = new RoutingStatementHandler(executor, mappedStatement, parameterObject, rowBounds, resultHandler, boundSql);
statementHandler = (StatementHandler) interceptorChain.pluginAll(statementHandler);
return statementHandler;
}public Executor newExecutor(Transaction transaction, ExecutorType executorType, boolean autoCommit) {
executorType = executorType == null ? defaultExecutorType : executorType;
executorType = executorType == null ? ExecutorType.SIMPLE : executorType;
Executor executor;
if (ExecutorType.BATCH == executorType) {
executor = new BatchExecutor(this, transaction);
} else if (ExecutorType.REUSE == executorType) {
executor = new ReuseExecutor(this, transaction);
} else {
executor = new SimpleExecutor(this, transaction);
}
if (cacheEnabled) {
executor = new CachingExecutor(executor, autoCommit);
}
executor = (Executor) interceptorChain.pluginAll(executor);
return executor;
}

以上4个方法都是Configuration的方法。这些方法在MyBatis的一个操作(新增,删除,修改,查询)中都会被执行到,执行的先后顺序是Executor,ParameterHandler,ResultSetHandler,StatementHandler(其中ParameterHandler和ResultSetHandler的创建是在创建StatementHandler[3个可用的实现类CallableStatementHandler,PreparedStatementHandler,SimpleStatementHandler]的时候,其构造函数调用的[这3个实现类的构造函数其实都调用了父类BaseStatementHandler的构造函数])。

这4个方法实例化了对应的对象之后,都会调用interceptorChain的pluginAll方法,InterceptorChain的pluginAll刚才已经介绍过了,就是遍历所有的拦截器,然后调用各个拦截器的plugin方法。

注意:拦截器的plugin方法的返回值会直接被赋值给原先的对象

由于可以拦截StatementHandler,这个接口主要处理sql语法的构建,因此比如分页的功能,可以用拦截器实现,只需要在拦截器的plugin方法中处理StatementHandler接口实现类中的sql即可,可使用反射实现。

4、Plugin类的使用

MyBatis还提供了 @Intercepts和 @Signature关于拦截器的注解。官网的例子就是使用了这2个注解,还包括了Plugin类的使用:

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

下面我们就分析这3个 “新组合” 的源码,首先先看Plugin类的wrap方法:

public static Object wrap(Object target, Interceptor interceptor) {
Map<Class<?>, Set<Method>> signatureMap = getSignatureMap(interceptor);
Class<?> type = target.getClass();
Class<?>[] interfaces = getAllInterfaces(type, signatureMap);
if (interfaces.length > 0) {
return Proxy.newProxyInstance(
type.getClassLoader(),
interfaces,
new Plugin(target, interceptor, signatureMap));
}
return target;
}

Plugin类实现了InvocationHandler接口,很明显,我们看到这里返回了一个JDK自身提供的动态代理类。我们解剖一下这个方法调用的其他方法:

5、getSignatureMap方法

getSignatureMap方法:

private static Map<Class<?>, Set<Method>> getSignatureMap(Interceptor interceptor) {
Intercepts interceptsAnnotation = interceptor.getClass().getAnnotation(Intercepts.class);
if (interceptsAnnotation == null) { // issue #251
throw new PluginException("No @Intercepts annotation was found in interceptor " + interceptor.getClass().getName());
}
Signature[] sigs = interceptsAnnotation.value();
Map<Class<?>, Set<Method>> signatureMap = new HashMap<Class<?>, Set<Method>>();
for (Signature sig : sigs) {
Set<Method> methods = signatureMap.get(sig.type());
if (methods == null) {
methods = new HashSet<Method>();
signatureMap.put(sig.type(), methods);
}
try {
Method method = sig.type().getMethod(sig.method(), sig.args());
methods.add(method);
} catch (NoSuchMethodException e) {
throw new PluginException("Could not find method on " + sig.type() + " named " + sig.method() + ". Cause: " + e, e);
}
}
return signatureMap;
}

getSignatureMap方法解释:首先会拿到拦截器这个类的 @Interceptors注解,然后拿到这个注解的属性 @Signature注解集合,然后遍历这个集合,遍历的时候拿出 @Signature注解的type属性(Class类型),然后根据这个type得到带有method属性和args属性的Method。由于 @Interceptors注解的 @Signature属性是一个属性,所以最终会返回一个以type为key,value为Set的Map。

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

比如这个 @Interceptors注解会返回一个key为Executor,value为集合(这个集合只有一个元素,也就是Method实例,这个Method实例就是Executor接口的update方法,且这个方法带有MappedStatement和Object类型的参数)。这个Method实例是根据 @Signature的method和args属性得到的。如果args参数跟type类型的method方法对应不上,那么将会抛出异常。

6、getAllInterfaces

getAllInterfaces方法:

private static Class<?>[] getAllInterfaces(Class<?> type, Map<Class<?>, Set<Method>> signatureMap) {
Set<Class<?>> interfaces = new HashSet<Class<?>>();
while (type != null) {
for (Class<?> c : type.getInterfaces()) {
if (signatureMap.containsKey(c)) {
interfaces.add(c);
}
}
type = type.getSuperclass();
}
return interfaces.toArray(new Class<?>[interfaces.size()]);
}

getAllInterfaces方法解释:根据目标实例target(这个target就是之前所说的MyBatis拦截器可以拦截的类,Executor,ParameterHandler,ResultSetHandler,StatementHandler)和它的父类们,返回signatureMap中含有target实现的接口数组。

所以Plugin这个类的作用就是根据 @Interceptors注解,得到这个注解的属性 @Signature数组,然后根据每个 @Signature注解的type,method,args属性使用反射找到对应的Method。最终根据调用的target对象实现的接口决定是否返回一个代理对象替代原先的target对象。

比如MyBatis官网的例子,当Configuration调用newExecutor方法的时候,由于Executor接口的update(MappedStatement ms, Object parameter)方法被拦截器被截获。因此最终返回的是一个代理类Plugin,而不是Executor。这样调用方法的时候,如果是个代理类,那么会执行:

public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
try {
Set<Method> methods = signatureMap.get(method.getDeclaringClass());
if (methods != null && methods.contains(method)) {
return interceptor.intercept(new Invocation(target, method, args));
}
return method.invoke(target, args);
} catch (Exception e) {
throw ExceptionUtil.unwrapThrowable(e);
}
}

没错,如果找到对应的方法被代理之后,那么会执行Interceptor接口的interceptor方法。

这个Invocation类如下:

public class Invocation {
private Object target;
private Method method;
private Object[] args; public Invocation(Object target, Method method, Object[] args) {
this.target = target;
this.method = method;
this.args = args;
} public Object getTarget() {
return target;
} public Method getMethod() {
return method;
} public Object[] getArgs() {
return args;
} public Object proceed() throws InvocationTargetException, IllegalAccessException {
return method.invoke(target, args);
}}

它的proceed方法也就是调用原先方法(不走代理)。

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,487
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,903
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,736
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,487
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:8,127
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:5,289