Mybatis插件原理分析(一)
來源:程序員人生 發布時間:2016-12-12 15:46:03 閱讀次數:2895次
我們首先介紹1下Mybatis插件相干的幾個類,并對源碼進行了簡單的分析。
Mybatis插件相干的接口或類有:Intercept、InterceptChain、Plugin和Invocation,這幾個接口或類實現了全部Mybatis插件流程。
Interceptor:1個接口,是實現自己功能需要實現的接口
源碼以下:
/**
* @author Clinton Begin
*/
public interface Interceptor {
//在此方法中實現自己需要的功能,最后履行invocation.proceed()方法,實際就是調用method.invoke(target, args)方法,調用代理類
Object intercept(Invocation invocation) throws Throwable;
//這個方法是將target生成代理類
Object plugin(Object target);
//在xml中注冊Intercept是配置1些屬性
void setProperties(Properties properties);
}
InterceptorChain:有1個List<Interceptor> interceptors變量,來保存所有Interceptor的實現類
源碼以下:
/**
* @author Clinton Begin
*/
public class InterceptorChain {
//插件攔截器鏈
private final List<Interceptor> interceptors = new ArrayList<Interceptor>();
//把target變成代理類,這樣在運行target方法之前需要運行Plugin的invoke方法
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);
}
}
Invocation:1個比較簡單的類,主要的功能就是根據構造函數類履行代理類
源碼以下:
/**
* @author Clinton Begin
*/
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;
}
//其實mybatis的Interceptor終究還是調用的method.invoke方法
public Object proceed() throws InvocationTargetException, IllegalAccessException {
return method.invoke(target, args);
}
}
Plugin:Mybatis插件的核心類,它實現了代理接口InvocationHandler,是1個代理類
源碼詳解以下:
/**
* @author Clinton Begin
*/
//這個類是Mybatis攔截器的核心,大家可以看到該類繼承了InvocationHandler
//又是JDK動態代理機制
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;
}
//1個靜態方法,對1個目標對象進行包裝,生成代理類。
public static Object wrap(Object target, Interceptor interceptor) {
//首先根據interceptor上面定義的注解 獲得需要攔截的信息
Map<Class<?>, Set<Method>> signatureMap = getSignatureMap(interceptor);
Class<?> type = target.getClass();
Class<?>[] interfaces = getAllInterfaces(type, signatureMap);
//如果長度為>0 則返回代理類 否則不做處理
if (interfaces.length > 0) {
//創建JDK動態代理對象
return Proxy.newProxyInstance(
type.getClassLoader(),
interfaces,
new Plugin(target, interceptor, signatureMap));
}
return target;
}
//在履行Executor、ParameterHandler、ResultSetHandler和StatementHandler的實現類的方法時會調用這個方法
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
try {
//通過method參數定義的類 去signatureMap當中查詢需要攔截的方法集合
Set<Method> methods = signatureMap.get(method.getDeclaringClass());
//判斷是不是是需要攔截的方法,如果需要攔截的話就履行實現的Interceptor的intercept方法,履行完以后還是會履行method.invoke方法,不過是放到interceptor實現類中去實現了
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);
}
}
//根據攔截器接口(Interceptor)實現類上面的注解獲得相干信息
private static Map<Class<?>, Set<Method>> getSignatureMap(Interceptor interceptor) {
//獲得注解信息
Intercepts interceptsAnnotation = interceptor.getClass().getAnnotation(Intercepts.class);
// issue #251
//為空則拋出異常
if (interceptsAnnotation == null) {
throw new PluginException("No @Intercepts annotation was found in interceptor " + interceptor.getClass().getName());
}
//取得Signature注解信息
Signature[] sigs = interceptsAnnotation.value();
Map<Class<?>, Set<Method>> signatureMap = new HashMap<Class<?>, Set<Method>>();
//循環注解信息
for (Signature sig : sigs) {
//根據Signature注解定義的type信息去signatureMap當中查詢需要攔截方法的集合
Set<Method> methods = signatureMap.get(sig.type());
//第1次肯定為null 就創建1個并放入signatureMap
if (methods == null) {
methods = new HashSet<Method>();
signatureMap.put(sig.type(), methods);
}
try {
//找到sig.type當中定義的方法 并加入到集合
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;
}
//根據對象類型與signatureMap獲得接口信息
private static Class<?>[] getAllInterfaces(Class<?> type, Map<Class<?>, Set<Method>> signatureMap) {
Set<Class<?>> interfaces = new HashSet<Class<?>>();
//循環type類型的接口信息 如果該類型存在與signatureMap當中則加入到set當中去
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()]);
}
}
對Mybatis插件有1定了解的人應當知道,插件攔截的類是Executor、ParameterHandler、ResultSetHandler和StatementHandler的實現類,為何會這樣呢?在Configuration類中看1下代碼就明白了,可以看到在初始化Executor、ParameterHandler、ResultSetHandler和StatementHandler都會調用interceptorChain.pluginAll()這個函數,其實這樣以后各個接口的實現類就被代理類生成為目標類了。
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) {
return newExecutor(transaction, defaultExecutorType);
}
public Executor newExecutor(Transaction transaction, ExecutorType executorType) {
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);
}
executor = (Executor) interceptorChain.pluginAll(executor);
return executor;
}
生活不易,碼農辛苦
如果您覺得本網站對您的學習有所幫助,可以手機掃描二維碼進行捐贈