
Interceptor :
Intercepts:
Signature:
InterceptorChain:
Invocation:
Plugin:
PluginException:
動態(tài)代理
一定要動態(tài)代理相關(guān)的知識搞清楚.動態(tài)代理搞清楚了,看mybatis的plugin源碼,就會如魚得水.
什么是插件?
其實插件更準確的叫法應(yīng)該叫擴展點吧.哪些類和哪些方法可以被擴展,都是事先定義好的.用戶如何需要擴展,那么就按照規(guī)范,實現(xiàn)擴展的方法.
像下面的這個簡單的demo,我們支持Map的get是根據(jù)一個key,get相關(guān)的value,如果你要寫一個變態(tài)的方法,不管你get什么都返回"Always",那么你只要實現(xiàn)一個intercept,我們看到Invocation這個類,這個類是源碼里面被攔截的方法的調(diào)用參數(shù)相關(guān)信息,像返回"Always"這個攔截就沒有使用invocation,正常的攔截方法是,我們在invocation.proceed前搞點事情,或者要統(tǒng)計耗時,在proceed前后一起搞點事情.
我們先看看最簡單的用法.
我們要攔截的對象是Map的get方法,參數(shù)隨意.當我們寫單元測試get的時候,不管get什么都會返回Always.
因為我們的動態(tài)代理已經(jīng)重寫Map的get方法.
@Intercepts({
@Signature(type = Map.class, method = "get", args = {Object.class})})
public static class AlwaysMapPlugin implements Interceptor {
@Override
public Object intercept(Invocation invocation) {
//只是這個類沒有使用invocation,
return "Always";
}
}
@Test
void mapPluginShouldInterceptGet() {
Map map = new HashMap();
map = (Map) new AlwaysMapPlugin().plugin(map);
assertEquals("Always", map.get("Anything"));
}
那么我們再來看看pagehelp是怎么使用的?
@Intercepts(
{
@Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class}),
@Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class, CacheKey.class, BoundSql.class}),
}
)
public class PageInterceptor implements Interceptor {
}
攔截了哪些方法是不是一目了然.
然后我們再一步一步的往下跟蹤吧.

這里面會拼接limit參數(shù).
ExecutorUtil.pageQuery(dialect, executor,
ms, parameter, rowBounds, resultHandler, boundSql, cacheKey);
public static <E> List<E> pageQuery(Dialect dialect, Executor executor, MappedStatement ms, Object parameter,
RowBounds rowBounds, ResultHandler resultHandler,
BoundSql boundSql, CacheKey cacheKey) throws SQLException {
//判斷是否需要進行分頁查詢
if (dialect.beforePage(ms, parameter, rowBounds)) {
//生成分頁的緩存 key
CacheKey pageKey = cacheKey;
//處理參數(shù)對象
parameter = dialect.processParameterObject(***) throws SQLException {
//判斷是否需要進行分頁查詢
if (dialect.beforePage(ms, parameter, rowBounds)) {
//生成分頁的緩存 key
CacheKey pageKey = cacheKey;
//處理參數(shù)對象
parameter = dialect.processParameterObject(ms, parameter, boundSql, pageKey);
//調(diào)用方言獲取分頁 sql
String pageSql = dialect.getPageSql(ms, boundSql, parameter, rowBounds, pageKey);
BoundSql pageBoundSql = new BoundSql(ms.getConfiguration(), pageSql, boundSql.getParameterMappings(), parameter);
Map<String, Object> additionalParameters = getAdditionalParameter(boundSql);
//設(shè)置動態(tài)參數(shù)
for (String key : additionalParameters.keySet()) {
pageBoundSql.setAdditionalParameter(key, additionalParameters.get(key));
}
//對 boundSql 的攔截處理
if (dialect instanceof BoundSqlInterceptor.Chain) {
pageBoundSql = ((BoundSqlInterceptor.Chain) dialect).doBoundSql(BoundSqlInterceptor.Type.PAGE_SQL, pageBoundSql, pageKey);
}
//執(zhí)行分頁查詢
return executor.query(ms, parameter, RowBounds.DEFAULT, resultHandler, pageKey, pageBoundSql);
} else {
//不執(zhí)行分頁的情況下,也不執(zhí)行內(nèi)存分頁
return executor.query(ms, parameter, RowBounds.DEFAULT, resultHandler, cacheKey, boundSql);
}
}
y);
//調(diào)用方言獲取分頁 sql.這里已經(jīng)有l(wèi)imit了.
String pageSql = dialect.getPageSql(ms, boundSql, parameter, rowBounds, pageKey);
BoundSql pageBoundSql = new BoundSql(ms.getConfiguration(), pageSql, boundSql.getParameterMappings(), parameter);
Map<String, Object> additionalParameters = getAdditionalParameter(boundSql);
//設(shè)置動態(tài)參數(shù)
for (String key : additionalParameters.keySet()) {
pageBoundSql.setAdditionalParameter(key, additionalParameters.get(key));
}
//對 boundSql 的攔截處理
if (dialect instanceof BoundSqlInterceptor.Chain) {
pageBoundSql = ((BoundSqlInterceptor.Chain) dialect).doBoundSql(BoundSqlInterceptor.Type.PAGE_SQL, pageBoundSql, pageKey);
}
//執(zhí)行分頁查詢.參數(shù)拼裝好了,交給executor去執(zhí)行了.
return executor.query(ms, parameter, RowBounds.DEFAULT, resultHandler, pageKey, pageBoundSql);
} else {
//不執(zhí)行分頁的情況下,也不執(zhí)行內(nèi)存分頁
return executor.query(ms, parameter, RowBounds.DEFAULT, resultHandler, cacheKey, boundSql);
}
}
MySqlDialect.getPageSql.
@Override
public String getPageSql(String sql, Page page, CacheKey pageKey) {
StringBuilder sqlBuilder = new StringBuilder(sql.length() + 14);
sqlBuilder.append(sql);
if (page.getStartRow() == 0) {
sqlBuilder.append("\n LIMIT ? ");
} else {
sqlBuilder.append("\n LIMIT ?, ? ");
}
return sqlBuilder.toString();
}
如果我們要自己寫個分庫分表的組件,是不是也很容易實現(xiàn)了呢?
相關(guān)類分析
Interceptor
Object intercept(Invocation invocation) throws Throwable;
//target:需要攔截的方法,給target生成動態(tài)代理
default Object plugin(Object target) {
return Plugin.wrap(target, this);
}
Plugin
其實我們不需要看這個類,只看第一個demo,就應(yīng)該知道Plugin肯定是實現(xiàn)了動態(tài)代理無非就是用的是jdk的還是cglib.
/**
* 這個類是繼承了InvocationHandler的
*
* @author Clinton Begin
*/
public class Plugin implements InvocationHandler {
//目標類
private final Object target;
//攔截器邏輯
private final Interceptor interceptor;
//方法簽名
private final Map<Class<?>, Set<Method>> signatureMap;
//私有的構(gòu)造器,不暴露出去.只有wrap才有權(quán)限調(diào)用.
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();
Class<?>[] interfaces = getAllInterfaces(type, signatureMap);
if (interfaces.length > 0) {
//生成代理對象
return Proxy.newProxyInstance(
type.getClassLoader(),
interfaces,
new Plugin(target, interceptor, signatureMap));
}
//返回原對象,不生成代理
return target;
}
//在 invoke() 方法中,Plugin 會檢查當前要執(zhí)行的方法是否在 signatureMap 集合中,
//如果在其中的話,表示當前待執(zhí)行的方法是我們要攔截的目標方法之一,也就會調(diào)用 intercept() 方法執(zhí)行代理邏輯;
//如果未在其中的話,則表示當前方法不應(yīng)被代理,直接執(zhí)行當前的方法即可。
@Override
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)) {
//最終會執(zhí)行用戶傳入的攔截方法
return interceptor.intercept(new Invocation(target, method, args));
}
//直接調(diào)用.
return method.invoke(target, args);
} catch (Exception e) {
throw ExceptionUtil.unwrapThrowable(e);
}
}
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[] sigs = interceptsAnnotation.value();
Map<Class<?>, Set<Method>> signatureMap = new HashMap<>();
for (Signature sig : sigs) {
Set<Method> methods = signatureMap.computeIfAbsent(sig.type(), k -> new HashSet<>());
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<>();
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()]);
}
}
InterceptorChain
看名字就知道用了責(zé)任鏈這個設(shè)計模式.實現(xiàn)就很簡單了,一個list攔截器集合,然后遍歷這個集合,一個一個的給這個target生成動態(tài)代理.
然后看到獲取攔截器的時候,返回的是一個不可變list,代碼就更安全了,不會被外部隨意的添加危險代碼.
public class InterceptorChain {
//攔截器集合
private final List<Interceptor> interceptors = new ArrayList<>();
//核心:
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);
}
}
mybatis里plugin再哪里裝配的?
我們看一下這個調(diào)用方法,有四個地方,剛好是mybatis的四大對象.

//下面幾個方法是四大對象的創(chuàng)建過程:我們可以發(fā)現(xiàn),這幾個類對象的創(chuàng)建過程都調(diào)用了 InteceptorChain 的 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;
}
plugin包里就這幾個類,但是實現(xiàn)了及其靈活的擴展性,這個包雖然類很少,但是類的設(shè)計和類里面的代碼都及其的優(yōu)雅,各位讀者們,趕快去閱讀下大牛的代碼吧.