首頁  >  文章  >  Java  >  mybatis攔截器

mybatis攔截器

(*-*)浩
(*-*)浩轉載
2019-09-03 16:41:131845瀏覽

攔截器的一個作用是我們可以攔截某些方法的調用,我們可以選擇在這些被攔截的方法執行前後加上某些邏輯,或者丟棄這些被攔截的方法而執行自己的邏輯。

mybatis攔截器

如對於mybatis的Executor,有幾種實作:BatchExecutor,ReuseExecutor、SimpleExecutor和CachingExecutor,當這幾種Executor介面的query方法無法滿足我們的要求的時候,我們就可以建立一個攔截器來實現自己的query方法;攔截器一般採用aop動態實作。

攔截器原理

對於mybatis,我們可以透過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方法主要是用於封裝目標對象,透過此方法我們可以決定是否要進行攔截進而決定返回什麼樣的目標對象。

intercept方法就是要進行攔截的時候執行的方法。 setProperties主要用於在設定檔中指定屬性,這個方法在Configuration初始化目前的Interceptor時就會執行.在mybatis中有一個plugin類,該類別包括靜態方法wrap,透過該方法可以決定需要傳回的物件是目標對象還是代理。

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, Set> signatureMap;
 
    private Plugin(Object target, Interceptor interceptor, Map, Set> signatureMap) {
        this.target = target;
        this.interceptor = interceptor;
        this.signatureMap = signatureMap;
    }
 
    public static Object wrap(Object target, Interceptor interceptor) {
        //解析获取需要拦截的类以及方法{*}
        Map, Set> signatureMap = getSignatureMap(interceptor);
        Class type = target.getClass();
        //解析type是否存在需要拦截的接口{*}
        Class[] interfaces = getAllInterfaces(type, signatureMap);
        //决定返回的对象是否为代理{*}
        if (interfaces.length > 0) {
            return Proxy.newProxyInstance(
                type.getClassLoader(),
                interfaces,
                new Plugin(target, interceptor, signatureMap));
        }
        //返回原目标对象
        return target;
    }
 
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        try {
            Set methods = signatureMap.get(method.getDeclaringClass());
            //如果当前执行的方法是定义的需要拦截的方法,则把目标对象,要拦截的方法以及参数封装为一个Invocation对象传递给拦截器方法intercept;
            //Invocation中定义了定义了一个proceed方法,其逻辑就是调用当前方法,所以如果在intercept中需要继续调用当前方法的话可以调用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);
        }
    }
 
    //根据注解解析需要拦截的方法
    //两个重要的注解:@Intercepts以及其值其值@Signature(一个数组)
    //@Intercepts用于表明当前的对象是一个Interceptor
    //@Signature则表明要拦截的接口、方法以及对应的参数类型。
    private static Map, Set> 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, Set> signatureMap = new HashMap, Set>();
        for (Signature sig : sigs) {
            Set methods = signatureMap.get(sig.type());
            if (methods == null) {
                methods = new HashSet();
                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, Set>  signatureMap) {
        Set> interfaces = new HashSet>();
        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()]);
    }
}

攔截器實例

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標記了這是一個Interceptor,透過@Signatrue設計攔截點:攔截Executor介面中參數類型為MappedStatement、 Object、RowBounds和ResultHandler的query方法;intercept方法呼叫invocation的proceed方法,使目前方法正常呼叫。

攔截器的註冊

註冊攔截器是透過在Mybatis設定檔中plugins元素下的plugin元素來進行的,Mybatis在註冊定義的攔截器時會先把對應攔截器下面的所有property透過Interceptor的setProperties方法注入。如:


    
        
    

以上是mybatis攔截器的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:csdn.net。如有侵權,請聯絡admin@php.cn刪除