很不错的文章 MyBatis整体预览(二) 2012-04-18
本文将介绍MyBatis的插件实现原理
一、MyBatis为开发者提供了非常丰富的接口,以满足开发者扩充自己的功能。将扩展的插件配置到configuration的plugins的标签中,那么mybatis自动将插件插入到你想执行的地方。在《MyBatis整体预览(一)》中,曾介绍MyBatis允许开发者在StatementHandler、ResultSetHandler、ParameterHandler以及Executor插入自己想执行的代码。下面将详细介绍从我们定制自己的插件到插件是如何被调用的来进行分析。
首先,要开发MyBatis的插件需要实现org.apache.ibatis.plugin.Interceptor接口,这个接口将会要求实现几个方法:intercept()、plugin()及setProperties(),intercept方法是开发人员所要执行的操作,plugin是将你插件放入到MyBatis的插件集合中去,而setProperties这是在你配置你插件的时候将plugins/plugin/properties的值设置到该插件中。这是实现自己插件的几个步骤,注意:一般在plugin方法中只写Plugin.wrap(target,this),target一般是你要拦截的对象,this这是当前的插件,在plugin方法参数中有个plugin(Object target),这个target类型就是StatementHandler、ResultSetHandler、ParameterHandler以及Executor中的一个。这里就插件的基本结构和方法进行了介绍。下面将对MyBatis如何获得开发人员开发的插件,以及具体执行的过程进行分析。
在《MyBatis整体预览(一)》中,对MyBatis的整个执行过程进行了一个介绍,主要是对Configuration对象的初始化过程进行了比较详细的介绍。当然,在Configuration初始化的过程中当然也包括对开发人员自己的插件进行初始化,并进行保存插件对象。
在XMLConfigBuilder的parsetConfiguration里面调用了pluginElement方法,这个方法将会解析开发人员配置在configuration中的plugin标签下面的元素。执行代码如下:
[java] 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);
}
}
}
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);
}
}
}
这个方法里面调用了configuration类中的addInterceptor方法,将插件实例添加到configuration对象中,那么让我们看看configuration里面对插件对象做了什么:
[java] public void addInterceptor(Interceptor interceptor) {
interceptorChain.addInterceptor(interceptor);
}
public void addInterceptor(Interceptor interceptor) {
interceptorChain.addInterceptor(interceptor);
}
这就是在configuration类中的这个addInterceptor方法,他将这个插件添加到一个链中,那么这个拦截器链是怎样的呢?
[java] 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 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);
} }
这个类很简单,直接将这个插件添加到了一个List对象集合中。你可能会发现上面还有一个pluginAll方法,并且在该方法里面调用了插件的plugin方法。大家是否明白了,这个plugin方法里面上面已经介绍,只是执行了Plugin.wrap(target,this)段代码。那么现在就有个几个问题:第一、这个pluginAll方法什么时候调用,还有就是Plugin.wrap(target,this),这段代码是干什么用的。理解清楚这两个问题,那么MyBatis的插件开发过程就完全理解了。
首先让我们开看看如何调用pluginAll方法的。在Configuration类中会发现一下几个方法:
[java] public ParameterHandler newParameterHandler(MappedStatement mappedStatement, Object parameterObject, BoundSql boundSql) {
ParameterHandler parameterHandler = new DefaultParameterHandler(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 = mappedStatement.hasNestedResultMaps() ? new NestedResultSetHandler(executor, mappedStatement, parameterHandler, resultHandler, boundSql,
rowBounds) : new FastResultSetHandler(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;
}
public ParameterHandler newParameterHandler(MappedStatement mappedStatement, Object parameterObject, BoundSql boundSql) {
ParameterHandler parameterHandler = new DefaultParameterHandler(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 = mappedStatement.hasNestedResultMaps() ? new NestedResultSetHandler(executor, mappedStatement, parameterHandler, resultHandler, boundSql,
rowBounds) : new FastResultSetHandler(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;
}
可以很清楚看到这几个方法里面都调用了pluginAll方法。看了这几个方法名不用我解释这些方法是做什么的了吧?这就是我为什么说:MyBatis允许开发者在StatementHandler、ResultSetHandler、ParameterHandler以及Executor插入自己想执行的代码。pluginAll都是将new出来的对象传递过去,这就是target。这里就对pluginAll方法进行了介绍。那么接下来就对插件的核心部分进行介绍。
Plugin.wrap(target,this)这段代码是做了什么事?在这里我将为大家解开这神秘的面纱。首先看看wrap方法是做了什么:
[java] 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;
}
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;
}
这个方法有来两个参数,第一个是target,第二个是interceptor。target就是我们要拦截的对象,及就是我们插件要放入到那个对象的代码中去,而interceptor就是开发人员开发的插件对象,此处貌似叫插件不是很合里,叫做拦截器更为合理,因为他是拦截MyBatis的执行过程,从而插入开发人员自己想执行的代码。此处就不就此问题纠结太久。发现在wrap方法里面第一行就调用了getSignatureMap方法,看到Signature这个单词不知是否很熟悉,这个在我们定义自己插件的时候貌似用到了:
[java] @Intercepts( {@Signature(type = StatementHandler.class, method = "prepare", args = {Connection.class})})
public class StatementHandlerInterceptor implements Interceptor {
private String DIALECT ;
public String getDIALECT() {
return DIALECT;
}
public void setDIALECT(String dIALECT) {
DIALECT = dIALECT;
}
@Override
public Object intercept(Invocation invocation) throws Throwable {
RoutingStatementHandler statement = (RoutingStatementHandler)invocation.getTarget();
PreparedStatementHandler handler = (PreparedStatementHandler)ReflectUtil.getFieldValue(statement,
"delegate");
RowBounds rowBounds = (RowBounds)ReflectUtil.getFieldValue(handler,
"rowBounds");
if(rowBounds!=null)
{
if (rowBounds.getLimit() > 0
&& rowBounds.getLimit() < RowBounds.NO_ROW_LIMIT)
{
BoundSql boundSql = statement.getBoundSql();
String sql = boundSql.getSql();
Dialect dialect = (Dialect)Class.forName(DIALECT).newInstance();
sql = dialect.getLimitString(sql,
rowBounds.getOffset(),
rowBounds.getLimit());
ReflectUtil.setFieldValue(boundSql, "sql", sql);
}
}
return invocation.proceed();
}
@Override
public Object plugin(Object target) {
return Plugin.wrap(target, this);
}
@Override
public void setProperties(Properties arg0) {
}
}
@Intercepts( {@Signature(type = StatementHandler.class, method = "prepare", args = {Connection.class})})
public class StatementHandlerInterceptor implements Interceptor {
private String DIALECT ;
public String getDIALECT() {
return DIALECT;
} public void setDIALECT(String dIALECT) {
DIALECT = dIALECT;
} @Override
public Object intercept(Invocation invocation) throws Throwable { RoutingStatementHandler statement = (RoutingStatementHandler)invocation.getTarget();
PreparedStatementHandler handler = (PreparedStatementHandler)ReflectUtil.getFieldValue(statement,
"delegate");
RowBounds rowBounds = (RowBounds)ReflectUtil.getFieldValue(handler,
"rowBounds");
if(rowBounds!=null)
{
if (rowBounds.getLimit() > 0
&& rowBounds.getLimit() < RowBounds.NO_ROW_LIMIT)
{
BoundSql boundSql = statement.getBoundSql();
String sql = boundSql.getSql();
Dialect dialect = (Dialect)Class.forName(DIALECT).newInstance();
sql = dialect.getLimitString(sql,
rowBounds.getOffset(),
rowBounds.getLimit());
ReflectUtil.setFieldValue(boundSql, "sql", sql);
}
}
return invocation.proceed();
} @Override
public Object plugin(Object target) {
return Plugin.wrap(target, this);
} @Override
public void setProperties(Properties arg0) { }
}
上面那段代码是我实现的一个拦截StatementHandler的prepare方法的插件。看到我在配置拦截目标的时候用到了这样一个注解:
@Intercepts( {@Signature(type = StatementHandler.class, method = "prepare", args = {Connection.class})})
这里面有个@Signature注解,这个单词是否和我上面讲到的一个方法名中包含这个单词。对,就是getSignatureMap这个方法。可以很容易想到这个方法就是处理这个注解的。接下来展开看一下getSignatureMap方法所要执行的操作。
[python] 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;
}
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;
}
该方法的第一句话就是获得Intercepts注解,这种方法应该很容易理解。那么接下来将获得在Intercepts里面的参数@Signature注解内容,在该注解中包含三个参数,分别是type,method,args。Type指定要拦截的类对象,method是指明要拦截该类的哪个方法,第三个是指明要拦截的方法参数集合。在Intercepts中可以配置多个@Signature。那么便对这写值进行遍历,已获得对应的type、method以及args。最终是获得一个HashMap对象,这些对象里面的键是类对象,而值是指定的类中方法对象。执行该端程序之后,更具target的classLoader和接口,来创建一个代理,并且,InvocationHandler是创建一个新的Plugin对象,同时将target,interceptor以及signatureMap传递给Plugin对象,当然,这里的Plugin也实现了Invocation接口。那么target对象所有的方法调用都会触发Plugin中的invoke方法,那么这里将执行开发者所有插入的操作。
[java] 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);
}
}
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);
}
}
发现,此处将判断,复合拦截要求的将执行插件的intercept方法,而在intercept方法里面放入了开发者所要执行的操作。那么此时,就成功的调用了开发者开发的MyBatis的插件了。现在来梳理一下执行的过程。
首先,开发者需要实现MyBatis的Interceptor接口,并主要要实现interceptor和plugin方法,而setProperties()当你配置了property就需要实现,没有,那么可以不用实现。实现接口后,那么就要将插件配置到MyBatis中去,然后通过XMLConfigBuilder来实例化插件对象,并将他们放到Configuration对象的InterceptChain对象的List集合中,然后在Configuration各种new的方法中调用InterceptChain的pluginAll方法,这里面将调用各个插件的plugin方法,这个方法里面则就调用Plugin的wrap方法,这个方法将要传入target和this(也就是插件自身对象)。那么在Plugin对象里面将创建一个代理对象,并且为这个代理对象创建一个InvocationHandler对象,这里将拦截代理对象的所有方法执行过程,及触发invoke方法,这里将执行实现的插件行为。这就是MyBatis的插件实现以及执行的过程。可能其中存在很多疑惑,但大致的流程应该都有,希望能够给大家带来帮助。
本文到此已结束!后期有时间也会发布关于MyBatis的相关内容!如有不对还望大家指出!大家相互学习,相互进步!