介绍
MyBatis框架允许用户通过自定义拦截器的方式改变SQL的执行行为,例如在SQL执行时追加SQL分页语法,从而达到简化分页查询的目的。用户自定义的拦截器也被称为MyBatis插件,本章我们就来分析一下MyBatis插件的实现原理以及如何开发一个插件。
拦截器的注册过程
为了弄清楚MyBatis插件的实现原理,我们可以从插件的配置及解析过程开始分析。在MyBatis主配置文件中,可以通过标签注册用户自定义的插件信息,例如:
<plugins>
<plugin interceptor="com.blog4java.plugin.pager.PageInterceptor">
<property name="databaseType" value="hsqldb"/>
</plugin>
<plugin interceptor="com.blog4java.plugin.slowsql.SlowSqlInterceptor">
<property name="limitSecond" value="0"/>
</plugin>
</plugins>
MyBatis的插件实际上就是一个拦截器,Configuration类中维护了一个InterceptorChain的实例,代码如下:
public class Configuration {
......
protected final InterceptorChain interceptorChain = new InterceptorChain();
......
public void addInterceptor(Interceptor interceptor) {
interceptorChain.addInterceptor(interceptor);
}
......
}
interceptorChain属性是一个拦截器链,用于存放通过标签注册的所有拦截器,Configration类中还定义了一个addInterceptor()方法,用于向拦截器链中添加拦截器。MyBatis框架在应用启动时会对标签进行解析。下面是XMLConfigBuilder类的pluginElement()方法解析标签的过程:
private void pluginElement(XNode parent) throws Exception {
if (parent != null) {
for (XNode child : parent.getChildren()) {
// 获取<plugin>标签的interceptor属性
String interceptor = child.getStringAttribute("interceptor");
// 获取拦截器属性,转换为Properties对象
Properties properties = child.getChildrenAsProperties();
// 创建拦截器实例
Interceptor interceptorInstance = (Interceptor) resolveClass(interceptor).newInstance();
// 设置拦截器实例属性信息
interceptorInstance.setProperties(properties);
// 將拦截器实例添加到拦截器链中
configuration.addInterceptor(interceptorInstance);
}
}
}
如上面的代码所示,在XMLConfigBuilder类的pluginElement()方法中,首先获取标签的interceptor属性,然后获取用户指定的拦截器属性并转换为Properties对象,然后通过Java的反射机制实例化拦截器对象,设置完拦截器对象的属性信息后,将拦截器对象添加到Configuration类中维护的拦截器链中。
拦截器的执行过程
用户自定义的插件只能对MyBatis中的4种组件的方法进行拦截,这4种组件及方法如下:
-
Executor(update, query, flushStatements, commit, rollback, getTransaction, close, isClosed)
-
ParameterHandler(getParameterObject, setParameters)
-
ResultSetHandler(handleResultSets, handleOutputParameters)
-
StatementHandler(prepare, parameterize, batch, update, query)
MyBatis使用工厂方法创建Executor、ParameterHandler、ResultSetHandler、StatementHandler组件的实例,其中一个原因是可以根据用户配置的参数创建不同实现类的实例;另一个比较重要的原因是可以在工厂方法中执行拦截逻辑。我们不妨看一下Configuration类中这些工厂方法的实现,代码如下:
public class Configuration {
......
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) {
return newExecutor(transaction, defaultExecutorType);
}
public Executor newExecutor(Transaction transaction, ExecutorType executorType) {
executorType = executorType == null ? defaultExecutorType : executorType;
executorType = executorType == null ? ExecutorType.SIMPLE : executorType;
Executor executor;
// 根据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);
}
// 如果cacheEnabled属性为ture,这使用CachingExecutor对上面创建的Executor进行装饰
if (cacheEnabled) {
executor = new CachingExecutor(executor);
}
// 执行拦截器链的拦截逻辑
executor = (Executor) interceptorChain.pluginAll(executor);
return executor;
}
......
}
如上面的代码所示,在Configuration类的newParameterHandler()、newResultSetHandler()、newStatementHandler()、newExecutor()这些工厂方法中,都调用了InterceptorChain对象的pluginAll()方法,pluginAll()方法返回ParameterHandler、ResultSetHandler、StatementHandler或者Executor对象的代理对象,拦截逻辑都是在代理对象中完成的。这就解释了为什么MyBatis自定义插件只能对Executor、ParameterHandler、ResultSetHandler、StatementHandler这4种组件的方法进行拦截。
接下来我们再来了解一下拦截器链InterceptorChain类的实现,代码如下:
public class InterceptorChain {
// 通过List对象维护所有拦截器实例
private final List<Interceptor> interceptors = new ArrayList<Interceptor>();
// 调用所有拦截器对象的plugin()方法执行拦截逻辑
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);
}
}
在InterceptorChain类中通过一个List对象维护所有的拦截器实例,在InterceptorChain的pluginAll()方法中,会调用所有拦截器实例的plugin()方法,该方法返回一个目标对象的代理对象。
MyBatis中所有用户自定义的插件都必须实现Interceptor接口,该接口的定义如下:
public interface Interceptor {
Object intercept(Invocation invocation) throws Throwable;
Object plugin(Object target);
void setProperties(Properties properties);
}
Interceptor接口中定义了3个方法,intercept()方法用于定义拦截逻辑,该方法会在目标方法调用时执行。plugin()方法用于创建Executor、ParameterHandler、ResultSetHandler或StatementHandler的代理对象,该方法的参数即为Executor、ParameterHandler、ResultSetHandler或StatementHandler组件的实例。setProperties()方法用于设置插件的属性值。需要注意的是,intercept()接收一个Invocation对象作为参数,Invocation对象中封装了目标对象的方法及参数信息。Invocation类的实现代码如下:
public class Invocation {
// 目标对象,即ParameterHandler、ResultSetHandler、StatementHandler或者Executor实例
private final Object target;
// 目标方法,即拦截的方法
private final Method method;
// 目标方法参数
private final 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;
}
/**
* 执行目标方法
* @return 目标方法执行结果
* @throws InvocationTargetException
* @throws IllegalAccessException
*/
public Object proceed() throws InvocationTargetException, IllegalAccessException {
return method.invoke(target, args);
}
}
如上面的代码所示,Invocation类中封装了目标对象、目标方法及参数信息,我们可以通过Invocation对象获取目标对象(Executor、ParameterHandler、ResultSetHandler或StatementHandler)的所有信息。另外,Invocation类中提供了一个proceed()方法,该方法用于执行目标方法的逻辑。所以在自定义插件类中,拦截逻辑执行完毕后一般都需要调用proceed()方法执行目标方法的原有逻辑。
为了便于用户创建Executor、ParameterHandler、ResultSetHandler或StatementHandler实例的代理对象,MyBatis中提供了一个Plugin工具类,该类的关键代码如下:
public class Plugin implements InvocationHandler {
//目标对象,即Executor、ParameterHandler、ResultSetHandler、StatementHandler对象
private final Object target;
// 用户自定义拦截器实例
private final Interceptor interceptor;
// Intercepts注解指定的方法
private final Map<Class<?>, Set<Method>> signatureMap;
private Plugin(Object target, Interceptor interceptor, Map<Class<?>, Set<Method>> signatureMap) {
this.target = target;
this.interceptor = interceptor;
this.signatureMap = signatureMap;
}
......
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
try {
// 如果该方法是Intercepts注解指定的方法,则调用拦截器实例的intercept()方法执行拦截逻辑
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);
}
}
......
}
如上面的代码所示,Plugin类实现了InvocationHandler接口,即采用JDK内置的动态代理方式创建代理对象。Plugin类中维护了Executor、ParameterHandler、ResultSetHandler或者StatementHandler类的实例,以及用户自定义的拦截器实例和拦截器中通过Intercepts注解指定的拦截方法。Plugin类的invoke()方法会在调用目标对象的方法时执行,在invoke()方法中首先判断该方法是否被Intercepts注解指定为被拦截的方法,如果是,则调用用户自定义拦截器的intercept()方法,并把目标方法信息封装成Invocation对象作为intercept()方法的参数。
Plugin类中还提供了一个静态的wrap()方法,该方法用于简化动态代理对象的创建,代码如下:
/**
* 该方法用于创建Executor、ParameterHandler、ResultSetHandler、StatementHandler的代理对象
* @param target
* @param interceptor
* @return
*/
public static Object wrap(Object target, Interceptor interceptor) {
// 调用getSignatureMap()方法获取自定义插件中,通过Intercepts注解指定的方法
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;
}
如上面的代码所示,wrap()方法的第一个参数为目标对象,即Executor、ParameterHandler、ResultSetHandler、StatementHandler类的实例;第二个参数为拦截器实例。在wrap()方法中首先调用getSignatureMap()方法获取Intercepts注解指定的要拦截的组件及方法,然后调用getAllInterfaces()方法获取当前Intercepts注解指定要拦截的组件的接口信息,接着调用Proxy类的静态方法newProxyInstance()创建一个动态代理对象。
Intercepts注解用于修饰拦截器类,告诉拦截器要对哪些组件的方法进行拦截。下面是Intercepts注解的一个使用案例:
@Intercepts({
@Signature(type = StatementHandler.class, method = "query", args = {Statement.class, ResultHandler.class}),
@Signature(type = StatementHandler.class, method = "update", args = {Statement.class}),
@Signature(type = StatementHandler.class, method = "batch", args = {Statement.class})
})
如上面的代码所示,通过Intercepts注解指定拦截StatementHandler组件的query()、update()、batch()方法
接下来我们就来了解一下Plugin类的getSignatureMap()方法解析Intercepts注解的过程,代码如下:
private static Map<Class<?>, Set<Method>> getSignatureMap(Interceptor interceptor) {
// 获取Intercepts注解信息
Intercepts interceptsAnnotation = interceptor.getClass().getAnnotation(Intercepts.class);
if (interceptsAnnotation == null) {
throw new PluginException("No @Intercepts annotation was found in interceptor " + interceptor.getClass().getName());
}
// 获取所有Signature注解信息
Signature[] sigs = interceptsAnnotation.value();
Map<Class<?>, Set<Method>> signatureMap = new HashMap<Class<?>, Set<Method>>();
// 对所有Signature注解进行遍历,把Signature注解指定拦截的组件及方法添加到Map中
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;
}
当我们需要自定义一个MyBatis插件时,只需要实现Interceptor接口,在intercept()方法中编写拦截逻辑,通过plugin()方法返回一个动态代理对象,通过setProperties()方法设置标签中配置的属性值即可。MyBatis源码中提供了一个自定义插件案例,代码如下:
@Intercepts({})
public class ExamplePlugin implements Interceptor {
private Properties properties;
@Override
public Object intercept(Invocation invocation) throws Throwable {
// TODO:自定义拦截逻辑
return invocation.proceed();
}
@Override
public Object plugin(Object target) {
// 调用Plugin类的wrap()方法返回一个动态代理对象
return Plugin.wrap(target, this);
}
@Override
public void setProperties(Properties properties) {
// 设置插件的属性信息
this.properties = properties;
}
public Properties getProperties() {
return properties;
}
}
如上面的代码所示,由于MyBatis提供了Plugin工具类用于创建拦截目标的代理对象,因此我们只需要在plugin()方法中调用Plugin.wrap()方法创建一个代理对象并返回即可。
总结
最后,我们再来回顾MyBatis插件的工作原理。以执行一个查询操作为例,通过前面章节的介绍,我们知道SqlSession是MyBatis中提供的面向用户的操作数据库的接口,而真正执行SQL操作的是Executor组件。MyBatis通过工厂模式创建Executor实例,Configuration类中提供了一个newExecutor()工厂方法,该方法返回的实际上是一个Executor的动态代理对象。
SqlSession获取Executor实例的过程如下:
(1)SqlSession中会调用Configuration类提供的newExecutor()工厂方法创建Executor对象。
(2)Configuration类中通过一个InterceptorChain对象维护了用户自定义的拦截器链。newExecutor()工厂方法中调用InterceptorChain对象的pluginAll()方法。
(3)InterceptorChain对象的pluginAll()方法中会调用自定义拦截器的plugin()方法。
(4)自定义拦截器的plugin()方法是由我们来编写的,通常会调用Plugin类的wrap()静态方法创建一个代理对象。
SqlSession获取到的Executor实例实际上已经是一个动态代理对象了。接下来我们就以SqlSession执行查询操作为例介绍自定义插件执行拦截逻辑的过程。当我们调用SqlSession对象的selectOne()方法执行查询操作时,大致会经历下面几个过程:
(1)SqlSession操作数据库需要依赖于Executor组件,SqlSession会调用Configuration对象的newExecutor()方法获取Executor的实例。
(2)SqlSession获取到的是Executor组件的代理对象,执行查询操作时会调用代理对象的query()方法。
(3)按照JDK动态代理机制,调用Executor代理对象的query()方法时,会调用Plugin类的invoke()方法。
(4)Plugin类的invoke()方法中会调用自定义拦截器对象的intercept()方法执行拦截逻辑。
(5)自定义拦截器对象的intercept()方法调用完毕后,调用目标Executor对象的query()方法。
(6)所有操作执行完毕后,会将查询结果返回给SqlSession对象。
学习记录,不断沉淀,终究会成为一个优秀的程序员,加油!
您的点赞、关注与收藏是我分享博客的最大赞赏!
博主博客地址: https://blog.youkuaiyun.com/qq_45701514