系列
- MyBatis拦截器原理介绍
- Mybatis拦截器改写请求参数和结果
- Mybatis 插件兼容动态SQL
- mybatis 参数解析流程附相关案例
- 再谈mybatis执行流程
Mybatis拦截器介绍
MyBatis 允许你在映射语句执行过程中的某一点进行拦截调用。默认情况下,MyBatis 允许使用插件来拦截的方法调用包括:
- Executor (update, query, flushStatements, commit, rollback, getTransaction, close, isClosed) 拦截执行器的方法
- ParameterHandler (getParameterObject, setParameters) 拦截参数的处理
- ResultSetHandler (handleResultSets, handleOutputParameters) 拦截结果集的处理
- StatementHandler (prepare, parameterize, batch, update, query) 拦截Sql语法和会话构建的处理
- mybatis在执行过程中按照Executor => StatementHandler => ParameterHandler => ResultSetHandler。
- Executor在执行过程中会创建StatementHandler,在创建StatementHandler过程中会创建 ParameterHandler和ResultSetHandler。
Mybatis拦截器的使用
---------定义拦截器
@Intercepts({
@Signature(type = ParameterHandler.class, method = "setParameters", args = PreparedStatement.class),
@Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class}),
@Signature(type = Executor.class, method = "createCacheKey", args = {MappedStatement.class, Object.class, RowBounds.class, BoundSql.class})
})
public class ExamplePlugin implements Interceptor {
private Properties properties = new Properties();
public Object intercept(Invocation invocation) throws Throwable {
// implement pre processing if need
Object returnObject = invocation.proceed();
// implement post processing if need
return returnObject;
}
public void setProperties(Properties properties) {
this.properties = properties;
}
}
---------mybatis全局xml配置
自定义一个mybatis的拦截器步骤包含:
- 定义实现org.apache.ibatis.plugin.Interceptor接口的类。
- 在mybatis的全局配置xml中配置插件plugin。
public interface Executor {
ResultHandler NO_RESULT_HANDLER = null;
int update(MappedStatement ms, Object parameter) throws SQLException;
List query(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, CacheKey cacheKey, BoundSql boundSql) throws SQLException;
List query(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler) throws SQLException;
Cursor queryCursor(MappedStatement ms, Object parameter, RowBounds rowBounds) throws SQLException;
List flushStatements() throws SQLException;
void commit(boolean required) throws SQLException;
void rollback(boolean required) throws SQLException;
CacheKey createCacheKey(MappedStatement ms, Object parameterObject, RowBounds rowBounds, BoundSql boundSql);
boolean isCached(MappedStatement ms, CacheKey key);
void clearLocalCache();
void deferLoad(MappedStatement ms, MetaObject resultObject, String property, CacheKey key, Class> targetType);
Transaction getTransaction();
void close(boolean forceRollback);
boolean isClosed();
void setExecutorWrapper(Executor executor);
}
public interface ParameterHandler {
Object getParameterObject();
void setParameters(PreparedStatement ps) throws SQLException;
}
public interface ResultSetHandler {
List handleResultSets(Statement stmt) throws SQLException;
Cursor handleCursorResultSets(Statement stmt) throws SQLException;
void handleOutputParameters(CallableStatement cs) throws SQLException;
}
public interface StatementHandler {
Statement prepare(Connection connection, Integer transactionTimeout) throws SQLException;
void parameterize(Statement statement) throws SQLException;
void batch(Statement statement) throws SQLException;
int update(Statement statement) hrows SQLException;
List query(Statement statement, ResultHandler resultHandler) hrows SQLException;
Cursor queryCursor(Statement statement) hrows SQLException;
BoundSql getBoundSql();
ParameterHandler getParameterHandler();
}
拦截点说明:
- 不同拦截点能够支持拦截的方法。
- 拦截方法的type、method、args等都取自上述方法。
Mybatis拦截器原理
拦截器的原理核心的内容在于拦截器配置解析、拦截器的职责链构造、拦截器的执行,串联上述功能后就能传统整体的流程。
拦截器解析
private void parseConfiguration(XNode root) {
try {
// issue #117 read properties first
propertiesElement(root.evalNode("properties"));
Properties settings = settingsAsProperties(root.evalNode("settings"));
loadCustomVfs(settings);
loadCustomLogImpl(settings);
typeAliasesElement(root.evalNode("typeAliases"));
pluginElement(root.evalNode("plugins")); // 解析插件相关的参数
objectFactoryElement(root.evalNode("objectFactory"));
objectWrapperFactoryElement(root.evalNode("objectWrapperFactory"));
reflectorFactoryElement(root.evalNode("reflectorFactory"));
settingsElement(settings);
// read it after objectFactory and objectWrapperFactory issue #631
environmentsElement(root.evalNode("environments"));
databaseIdProviderElement(root.evalNode("databaseIdProvider"));
typeHandlerElement(root.evalNode("typeHandlers"));
mapperElement(root.evalNode("mappers"));
} catch (Exception e) {
throw new BuilderException("Error parsing SQL Mapper Configuration. Cause: " + e, e);
}
}
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).getDeclaredConstructor().newInstance();
interceptorInstance.setProperties(properties);
configuration.addInterceptor(interceptorInstance); // 保存拦截器
}
}
}
public class InterceptorChain {
private final List interceptors = new ArrayList<>(); // 全局变量保存所有的拦截器
// 织入拦截器
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 getInterceptors() {
return Collections.unmodifiableList(interceptors);
}
}
拦截器解析说明:
- 负责解析XML配置文件解析所有的拦截器对象保存到拦截器链InterceptorChain 。
- InterceptorChain通过pluginAll植入拦截器。
拦截器织入
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) {
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);
}
// 插入拦截器
executor = (Executor) interceptorChain.pluginAll(executor);
return executor;
}
拦截器织入说明:
- 针对ParameterHandler 、ResultSetHandler 、StatementHandler 、Executor 的拦截器的植入都是通过interceptorChain.pluginAll来实现。
public class InterceptorChain {
private final List interceptors = new ArrayList<>();
public Object pluginAll(Object target) {
// 遍历所有的拦截器负责进行植入
for (Interceptor interceptor : interceptors) {
target = interceptor.plugin(target);
}
return target;
}
}
public interface Interceptor {
Object intercept(Invocation invocation) throws Throwable;
// 通过wrap织入单个拦截器
default Object plugin(Object target) {
return Plugin.wrap(target, this);
}
default void setProperties(Properties properties) {
// NOP
}
}
public class Plugin implements InvocationHandler {
public static Object wrap(Object target, Interceptor interceptor) {
// 解析拦截器的注解获取拦截的拦截点和对应的拦截方法
Map, Set> signatureMap = getSignatureMap(interceptor);
Class> type = target.getClass();
// 获取被拦截对应的信息构建JDK的动态代理
Class>[] interfaces = getAllInterfaces(type, signatureMap);
if (interfaces.length > 0) {
// 针对注解指定的interface进行拦截
return Proxy.newProxyInstance(
type.getClassLoader(),
interfaces,
new Plugin(target, interceptor, signatureMap));
}
return target;
}
}
拦截器织入说明:
- 拦截器织入依赖于JDK自带的Proxy.newProxyInstance动态代理来实现。
- 返回的对象是个Plugin对象的动态代理。
private static Map, Set> getSignatureMap(Interceptor interceptor) {
// 1、获取所有拦截的Intercepts注解
Intercepts interceptsAnnotation = interceptor.getClass().getAnnotation(Intercepts.class);
// issue #251
if (interceptsAnnotation == null) {
throw new PluginException("No @Intercepts annotation was found in interceptor " + interceptor.getClass().getName());
}
// 2、获取注解的内容
Signature[] sigs = interceptsAnnotation.value();
Map, Set> signatureMap = new HashMap<>();
// 3、遍历注解按照type + method维度进行构建
for (Signature sig : sigs) {
Set methods = MapUtil.computeIfAbsent(signatureMap, sig.type(), k -> new HashSet<>());
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;
}
private static Class>[] getAllInterfaces(Class> type, Map, Set> signatureMap) {
Set> interfaces = new HashSet<>();
while (type != null) {
// 获取拦截点对应的Interfaces并且在拦截点注解配置的的interface用以构建动态代理
for (Class> c : type.getInterfaces()) {
if (signatureMap.containsKey(c)) {
interfaces.add(c);
}
}
type = type.getSuperclass();
}
return interfaces.toArray(new Class>[0]);
}
拦截器织入说明:
- 通过解析注解@Intercepts注解@Signature来构建class + method两个维度的map对象。
- 以@Signature(type = ParameterHandler.class, method = "setParameters", args = PreparedStatement.class)为例,会构建key为ParameterHandler,value为setParameters的map
拦截器执行
public class Plugin implements InvocationHandler {
private final Object target;
private final Interceptor interceptor;
private final Map, Set> signatureMap;
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
try {
// 判断是否是被拦截的方法,如果是就通过拦截器进行处理
Set methods = signatureMap.get(method.getDeclaringClass());
if (methods != null && methods.contains(method)) {
// 由拦截器interceptor负责处理
return interceptor.intercept(new Invocation(target, method, args));
}
return method.invoke(target, args);
} catch (Exception e) {
throw ExceptionUtil.unwrapThrowable(e);
}
}
}
JDK动态代理
public class Main {
public static void main(String[] args) throws Exception {
final Dog dog = new Dog();
IDog proxy = (IDog)Proxy.newProxyInstance(Dog.class.getClassLoader(), Dog.class.getInterfaces(), new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
return method.invoke(dog, args);
}
});
proxy.eat();
Thread.sleep(100000);
}
}
-------------------------对应生成的动态代码
package com.sun.proxy;
import com.sunboy.IDog;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.lang.reflect.UndeclaredThrowableException;
public final class $Proxy0 extends Proxy implements IDog {
private static Method m1;
private static Method m3;
private static Method m2;
private static Method m0;
public $Proxy0(InvocationHandler invocationHandler) {
super(invocationHandler);
}
static {
try {
m1 = Class.forName("java.lang.Object").getMethod("equals", Class.forName("java.lang.Object"));
m3 = Class.forName("com.sunboy.IDog").getMethod("eat", new Class[0]);
m2 = Class.forName("java.lang.Object").getMethod("toString", new Class[0]);
m0 = Class.forName("java.lang.Object").getMethod("hashCode", new Class[0]);
return;
}
catch (NoSuchMethodException noSuchMethodException) {
throw new NoSuchMethodError(noSuchMethodException.getMessage());
}
catch (ClassNotFoundException classNotFoundException) {
throw new NoClassDefFoundError(classNotFoundException.getMessage());
}
}
public final boolean equals(Object object) {
try {
return (Boolean)this.h.invoke(this, m1, new Object[]{object});
}
catch (Error | RuntimeException throwable) {
throw throwable;
}
catch (Throwable throwable) {
throw new UndeclaredThrowableException(throwable);
}
}
public final String toString() {
try {
return (String)this.h.invoke(this, m2, null);
}
catch (Error | RuntimeException throwable) {
throw throwable;
}
catch (Throwable throwable) {
throw new UndeclaredThrowableException(throwable);
}
}
public final int hashCode() {
try {
return (Integer)this.h.invoke(this, m0, null);
}
catch (Error | RuntimeException throwable) {
throw throwable;
}
catch (Throwable throwable) {
throw new UndeclaredThrowableException(throwable);
}
}
public final void eat() {
try {
this.h.invoke(this, m3, null);
return;
}
catch (Error | RuntimeException throwable) {
throw throwable;
}
catch (Throwable throwable) {
throw new UndeclaredThrowableException(throwable);
}
}
}
- JDK动态代理生成的代理类如$Proxy0,通过arthas去反编译类。
- JDK动态代理通过反射获取Method对象用以后续的执行。