Exploring the principle of MyBatis interceptor and mybatis Interception
Introduction to MyBatis interceptor
MyBatis provides a plug-in function. Although called plug-in, it is actually an interceptor function. So what content does the interceptor intercept in MyBatis?
Let's go to the official website and take a look:
MyBatis allows you to intercept calls at a point during the execution of ing statements. By default, MyBatis allows the use of plug-ins to intercept method calls, including:
- Executor (update, query, flushStatements, commit, rollback, getTransaction, close, isClosed)
- ParameterHandler (getParameterObject, setParameters)
- ResultSetHandler (handleResultSets, handleOutputParameters)
- StatementHandler (prepare, parameterize, batch, update, query)
We can see some methods that can intercept the Executor interface, such as update, query, commit, rollback, and other methods of interfaces.
.
Overall summary:
- Methods for intercepting Actuators
- Processing of interception Parameters
- Process intercepted result sets
- Block SQL syntax Construction
Use of interceptor
Introduction and configuration of interceptor
First, let's take a look at the Interface Definition of the MyBatis Interceptor:
public interface Interceptor { Object intercept(Invocation invocation) throws Throwable; Object plugin(Object target); void setProperties(Properties properties);}
It is relatively simple and there are only three methods. By default, MyBatis does not have an implementation class for the interceptor interface. developers can implement the interceptor that meets their own needs.
The following is an interceptor instance on the MyBatis Website:
@Intercepts({@Signature( type= Executor.class, method = "update", args = {MappedStatement.class,Object.class})})public class ExamplePlugin implements Interceptor { public Object intercept(Invocation invocation) throws Throwable { return invocation.proceed(); } public Object plugin(Object target) { return Plugin.wrap(target, this); } public void setProperties(Properties properties) { }}
Global xml configuration:
<plugins> <plugin interceptor="org.format.mybatis.cache.interceptor.ExamplePlugin"></plugin></plugins>
This interceptor intercepts the update method of the Executor interface (in fact, the SqlSession addition, deletion, and modification operations). All the update methods that execute the executor will be intercepted by this interceptor.
Source code analysis
Next we will analyze the source code behind this code.
First, analyze the source File> configuration file:
XMLConfigBuilder parses the pluginElement private method of the MyBatis global configuration file:
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); } }}
The specific parsing code is actually relatively simple and will not be pasted. It is mainly to instantiate the class represented by the interceptor attribute in the plugin node through reflection. Then, call the addInterceptor method of the global Configuration class Configuration.
public void addInterceptor(Interceptor interceptor) { interceptorChain.addInterceptor(interceptor); }
This interceptorChain is an internal attribute of Configuration and its type is InterceptorChain, which is an interceptor chain. Let's take a look at its definition:
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); }}
Now we understand the parsing of the interceptor configuration and the ownership of the interceptor. Now let's look at why the interceptor intercepts these methods (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;}
The preceding four methods are Configuration methods. These methods are executed in an operation (add, delete, modify, query) of MyBatis. The execution sequence is Executor, ParameterHandler, ResultSetHandler, statementHandler (ParameterHandler and ResultSetHandler are created when you create StatementHandler [three available implementation classes: CallableStatementHandler, PreparedStatementHandler, SimpleStatementHandler, the constructor calls [the constructor of the three implementation classes actually calls the constructor of the parent class BaseStatementHandler]).
After the four methods instantiate the corresponding object, they will call the interceptorChain pluginAll method. The InterceptorChain pluginAll has just been introduced, that is, traversing all the interceptors, call the plugin method of each interceptor. Note: the return value of the plugin method of the interceptor is directly assigned to the original object.
Because StatementHandler can be intercepted, this interface mainly processes the construction of SQL syntax. For example, the paging function can be implemented by the interceptor, you only need to process the SQL statements in the StatementHandler interface implementation class in the plugin method of the interceptor. reflection can be used for implementation.
MyBatis also provides @ Intercepts and @ Signature Annotations on interceptor. The example on the official website uses these two annotations and also includes the use of the Plugin class:
@Overridepublic Object plugin(Object target) { return Plugin.wrap(target, this);}
Next we will analyze the source code of the three "New Combinations". First, let's look at the wrap method of the Plugin class:
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;}
The Plugin class implements the InvocationHandler interface. Obviously, a dynamic proxy class provided by JDK itself is returned. Let's take a look at other methods called by this method:
GetSignatureMap method:
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;}
The getSignatureMap method explains: first get the @ Interceptors annotation of the interceptor class, then get the attribute @ Signature annotation set of the annotation, and then traverse the set, during traversal, the type attribute (Class type) of the @ Signature annotation is obtained, and the method with the Method and args attributes is obtained based on the type. Because the @ Signature attribute of the @ Interceptors annotation is an attribute, a Map with type as key and value as Set <Method> is returned.
@Intercepts({@Signature( type= Executor.class, method = "update", args = {MappedStatement.class,Object.class})})
For example, the @ Interceptors annotation returns a key as Executor and a value as a set (this set has only one element, that is, the Method Instance. This Method instance is the update Method of the Executor interface, and this method has MappedStatement and Object-type parameters ). This Method instance is obtained based on @ Signature's method and args attributes. If the args parameter does not match the method of the type, an exception is thrown.
GetAllInterfaces method:
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()]);}
The getAllInterfaces method explains: according to the target instance target (this target is the class called MyBatis Interceptor to intercept, Executor, ParameterHandler, ResultSetHandler, StatementHandler) and its parent class, returns an array of interfaces implemented by target in signatureMap.
Therefore, the function of the Plugin class is to obtain the attribute @ Signature array of this annotation according to the @ Interceptors annotation, and then according to the type, method, the args attribute uses reflection to find the corresponding Method. Finally, the system determines whether to return a proxy object to replace the original target object based on the interface implemented by the called target object.
For example, in the example on the MyBatis website, when Configuration calls the newExecutor method, the update (MappedStatement MS, Object parameter) method of the Executor interface is intercepted by the interceptor. Therefore, a proxy class Plugin is returned instead of Executor. In this way, if the method is called as a proxy class, it will execute:
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); }}
If the corresponding method is found to be proxies, the Interceptor method of the interceptor interface will be executed.
The Invocation class is as follows:
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); }}
Its proceed method is to call the original method (without proxy ).
Summary
Among the three methods provided by the MyBatis interceptor interface, the plugin method is used for the construction process of some processors (Handler. The interceptor method is used to process the execution of the proxy class. The setProperties method is used to set interceptor properties.
In fact, we do not have to use the @ Interceptors, @ Signature annotation, and Plugin class to process the interceptor directly on the MyBatis website. We can also discard these three classes and perform corresponding operations based on the target instance type in the plugin method.
In general, the MyBatis interceptor is still very simple. The interceptor itself does not need many knowledge points. However, to learn the interceptor, you must be familiar with all interfaces in MyBatis, because the interceptor involves knowledge points of each interface.
Summary
The above section describes the principle of MyBatis Interceptor. I hope it will be helpful to you. If you have any questions, please leave a message and I will reply to you in a timely manner. Thank you very much for your support for the help House website!