攔截器的一個(gè)作用就是我們可以攔截某些方法的調(diào)用,我們可以選擇在這些被攔截的方法執(zhí)行前后加上某些邏輯,或者丟棄這些被攔截的方法而執(zhí)行自己的邏輯。
如對(duì)于mybatis的Executor,有幾種實(shí)現(xiàn):BatchExecutor,ReuseExecutor、SimpleExecutor和CachingExecutor,當(dāng)這幾種Executor接口的query方法無(wú)法滿足我們的要求的時(shí)候,我們就可以建立一個(gè)攔截器來(lái)實(shí)現(xiàn)自己的query方法;攔截器一般采用aop動(dòng)態(tài)實(shí)現(xiàn)。
攔截器原理
對(duì)于mybatis,我們可以通過(guò)interceptor接口定義自己的攔截器。interceptor接口定義:
package org.apache.ibatis.plugin; import java.util.Properties; public interface Interceptor { Object intercept(Invocation invocation) throws Throwable; Object plugin(Object target); void setProperties(Properties properties); }
plugin方法主要是用于封裝目標(biāo)對(duì)象,通過(guò)該方法我們可以決定是否要進(jìn)行攔截進(jìn)而決定返回什么樣的目標(biāo)對(duì)象。
intercept方法就是要進(jìn)行攔截的時(shí)候執(zhí)行的方法。setProperties主要用于在配置文件中指定屬性,這個(gè)方法在Configuration初始化當(dāng)前的Interceptor時(shí)就會(huì)執(zhí)行.在mybatis中有一個(gè)plugin類(lèi),該類(lèi)包括靜態(tài)方法wrap,通過(guò)該方法可以決定需要返回的對(duì)象是目標(biāo)對(duì)象還是代理。
package org.apache.ibatis.plugin; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import org.apache.ibatis.reflection.ExceptionUtil; public class Plugin implements InvocationHandler { private Object target; private Interceptor interceptor; private 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; } public static Object wrap(Object target, Interceptor interceptor) { //解析獲取需要攔截的類(lèi)以及方法{*} Map<Class<?>, Set<Method>> signatureMap = getSignatureMap(interceptor); Class<?> type = target.getClass(); //解析type是否存在需要攔截的接口{*} Class<?>[] interfaces = getAllInterfaces(type, signatureMap); //決定返回的對(duì)象是否為代理{*} if (interfaces.length > 0) { return Proxy.newProxyInstance( type.getClassLoader(), interfaces, new Plugin(target, interceptor, signatureMap)); } //返回原目標(biāo)對(duì)象 return target; } public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { try { Set<Method> methods = signatureMap.get(method.getDeclaringClass()); //如果當(dāng)前執(zhí)行的方法是定義的需要攔截的方法,則把目標(biāo)對(duì)象,要攔截的方法以及參數(shù)封裝為一個(gè)Invocation對(duì)象傳遞給攔截器方法intercept; //Invocation中定義了定義了一個(gè)proceed方法,其邏輯就是調(diào)用當(dāng)前方法,所以如果在intercept中需要繼續(xù)調(diào)用當(dāng)前方法的話可以調(diào)用invocation的procced方法; 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); } } //根據(jù)注解解析需要攔截的方法 //兩個(gè)重要的注解:@Intercepts以及其值其值@Signature(一個(gè)數(shù)組) //@Intercepts用于表明當(dāng)前的對(duì)象是一個(gè)Interceptor //@Signature則表明要攔截的接口、方法以及對(duì)應(yīng)的參數(shù)類(lèi)型。 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 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()]); } }
攔截器實(shí)例
package com.mybatis.interceptor; import java.sql.Connection; import java.util.Properties; import org.apache.ibatis.executor.Executor; import org.apache.ibatis.executor.statement.StatementHandler; import org.apache.ibatis.mapping.MappedStatement; import org.apache.ibatis.plugin.Interceptor; import org.apache.ibatis.plugin.Intercepts; import org.apache.ibatis.plugin.Invocation; import org.apache.ibatis.plugin.Plugin; import org.apache.ibatis.plugin.Signature; import org.apache.ibatis.session.ResultHandler; import org.apache.ibatis.session.RowBounds; @Intercepts( { @Signature(method = "query", type = Executor.class, args = { MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class })}) public class TestInterceptor implements Interceptor { public Object intercept(Invocation invocation) throws Throwable { Object result = invocation.proceed(); return result; } public Object plugin(Object target) { return Plugin.wrap(target, this); } public void setProperties(Properties properties) { String p = properties.getProperty("property"); } }
首先用@Intercepts標(biāo)記了這是一個(gè)Interceptor,通過(guò)@Signatrue設(shè)計(jì)攔截點(diǎn):攔截Executor接口中參數(shù)類(lèi)型為MappedStatement、Object、RowBounds和ResultHandler的query方法;intercept方法調(diào)用invocation的proceed方法,使當(dāng)前方法正常調(diào)用。
攔截器的注冊(cè)
注冊(cè)攔截器是通過(guò)在Mybatis配置文件中plugins元素下的plugin元素來(lái)進(jìn)行的,Mybatis在注冊(cè)定義的攔截器時(shí)會(huì)先把對(duì)應(yīng)攔截器下面的所有property通過(guò)Interceptor的setProperties方法注入。如:
<plugins> <plugin interceptor="com.mybatis.interceptor.TestInterceptor"> <property name="property" value="攔截器配置"/> </plugin> </plugins>