> Java > java지도 시간 > 본문

마이바티스 인터셉터

(*-*)浩
풀어 주다: 2019-09-03 16:41:13
앞으로
1974명이 탐색했습니다.

인셉터의 기능 중 하나는 특정 메서드의 호출을 가로챌 수 있다는 것입니다. 가로채는 메서드 실행 전후에 일부 논리를 추가하거나 가로채는 메서드를 삭제하고 실행하도록 선택할 수 있습니다. 우리 자신의 논리. 예를 들어, mybatis의 Executor에는 BatchExecutor, ReuseExecutor, SimpleExecutor 및 CachingExecutor와 같은 여러 가지 구현이 있습니다. Executor 인터페이스의 쿼리 메소드가 우리의 요구 사항을 충족할 수 없는 경우 인터셉터를 생성하여 자체 쿼리 메소드를 구현할 수 있습니다. 인터셉터는 일반적으로 aop를 사용하여 동적으로 구현됩니다.

인터셉터 원리

마이바티스 인터셉터

mybatis에서는 인터셉터 인터페이스를 통해 자체 인터셉터를 정의할 수 있습니다. 인터셉터 인터페이스 정의:

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);
}
로그인 후 복사

플러그인 메소드는 주로 대상 객체를 캡슐화하는 데 사용됩니다. 이 메소드를 통해 인터셉트할지 여부를 결정한 다음 반환할 대상 객체의 종류를 결정할 수 있습니다.

Intercept 메소드는 가로챌 때 실행되는 메소드입니다. setProperties는 주로 구성 파일에서 속성을 지정하는 데 사용됩니다. 이 메소드는 Configuration이 현재 인터셉터를 초기화할 때 실행됩니다. mybatis에는 정적 메소드 랩을 포함하는 플러그인 클래스가 있습니다. 반환될 개체 또는 에이전트입니다.

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) {
        //解析获取需要拦截的类以及方法{*}
        Map<Class<?>, Set<Method>> 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<Method> 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<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()]);
    }
}
로그인 후 복사

Interceptor 인스턴스

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를 사용하여 인터셉터로 표시하고 @Signatrue를 통해 차단 지점을 설계합니다. Executor를 차단합니다. 인터페이스 매개변수 유형이 MappedStatement, Object, RowBounds 및 ResultHandler인 쿼리 메소드는 호출의 진행 메소드를 호출하여 현재 메소드를 정상적으로 호출합니다.

인터셉터 등록

인터셉터 등록은 Mybatis 구성 파일의 플러그인 요소 아래에 있는 플러그인 요소를 통해 수행됩니다. 예 , Mybatis가 정의된 인터셉터를 등록하면 먼저 Interceptor의 setProperties 메소드를 통해 해당 인터셉터 아래의 모든 속성을 주입합니다. 예:

<plugins>
    <plugin interceptor="com.mybatis.interceptor.TestInterceptor">
        <property name="property" value="拦截器配置"/>
    </plugin>
</plugins>
로그인 후 복사

위 내용은 마이바티스 인터셉터의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

관련 라벨:
원천:csdn.net
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!