近期一個業(yè)務(wù)需要配置禁寫袁辈,想通過Mybatis的Plugin來做妙黍,于是有了這篇文章碾篡。先來看官網(wǎng)對Plugin的介紹(以下內(nèi)容來自官網(wǎng))
// MyBatis 允許你在映射語句執(zhí)行過程中的某一點(diǎn)進(jìn)行攔截調(diào)用砍的。默認(rèn)情況下驼卖,MyBatis 允許使用插件來攔截的方法調(diào)用包括:
Executor (update, query, flushStatements, commit, rollback, getTransaction, close, isClosed)
ParameterHandler (getParameterObject, setParameters)
ResultSetHandler (handleResultSets, handleOutputParameters)
StatementHandler (prepare, parameterize, batch, update, query)
也就是說氨肌,在mybatis的執(zhí)行流程中,支持Plugin的場景有且僅有:Executor酌畜、ParameterHandler怎囚、StatementHandler以及ResultSetHandler。針對我們的需求桥胞,剛開始打算直接從Executor入手恳守,實(shí)現(xiàn)禁寫并保存sql,下面是處理類
@Intercepts({
// 注意贩虾,這里的type只能是接口催烘,否則不會生效,具體原因參考下面的源碼
@Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class})
})
public class ForbidInterceptor implements Interceptor {
private Properties properties;
private static final Logger LOGGER = LoggerFactory.getLogger(ForbidInterceptor.class);
@Override
public Object intercept(Invocation invocation) throws Throwable {
Executor executor = (Executor)invocation.getTarget();
MappedStatement statement = (MappedStatement)invocation.getArgs()[0];
Object paramObject = invocation.getArgs()[1];
Configuration configuration = statement.getConfiguration();
StatementHandler handler = configuration.newStatementHandler(executor, statement, paramObject, RowBounds.DEFAULT, null, null);
// 簡單期間缎罢,拿到PreparedStatement颗圣,有點(diǎn)多此一舉,不如直接切PreparedStatmentHandler
PreparedStatement preparedStatement = (PreparedStatement) prepareStatement(handler,executor.getTransaction().getConnection(),executor.getTransaction());
String rawSql = preparedStatement.toString();
int updateIndex = rawSql.indexOf("update") == -1 ? rawSql.indexOf("insert") : -1;
if(updateIndex == -1 ){
return invocation.proceed();
}
//業(yè)務(wù)邏輯省略屁使,這里僅打印執(zhí)行sql在岂,然后直接返回1,并不會真實(shí)執(zhí)行sql
rawSql = rawSql.substring(updateIndex);
LOGGER.info("row sql : " + rawSql);
return (Object)1;
}
@Override
public Object plugin(Object target) {
return Plugin.wrap(target,this);
}
@Override
public void setProperties(Properties properties) {
this.properties = properties;
}
// 這里參照mybatis對preparedStatement的處理
private Statement prepareStatement(StatementHandler handler, Connection connection, Transaction transaction) throws SQLException {
Statement stmt;
stmt = handler.prepare(connection, transaction.getTimeout());
handler.parameterize(stmt);
return stmt;
}
雖然可以實(shí)現(xiàn)禁寫的目的蛮寂,但是就像代碼中注釋的那樣蔽午,有點(diǎn)多此一舉;所以酬蹋,直接來切PreparedStatementHandler,下面是處理類
@Intercepts({
@Signature(type = StatementHandler.class, method = "update", args = {Statement.class})
})
public class ForbidInterceptorForMmc implements Interceptor {
private Properties properties;
private static final Logger LOGGER = LoggerFactory.getLogger(ForbidInterceptor.class);
@Override
public Object intercept(Invocation invocation) throws Throwable {
PreparedStatement ps = (PreparedStatement)invocation.getArgs()[0];
if(Objects.nonNull(ps)){
// 省略業(yè)務(wù)邏輯及老,僅打印sql
String rawSql = ps.toString();
int updateIndex = rawSql.indexOf("update") == -1 ? rawSql.indexOf("insert") : -1;
// 非更新語句抽莱,直接執(zhí)行
if(updateIndex == -1 ){
return invocation.proceed();
}
rawSql = rawSql.substring(updateIndex);
LOGGER.info("row sql : " + rawSql);
}
return 1;
}
@Override
public Object plugin(Object target) {
return Plugin.wrap(target,this);
}
@Override
public void setProperties(Properties properties) {
this.properties = properties;
}
結(jié)果也比較簡單,可以看到具體待執(zhí)行的sql(實(shí)際業(yè)務(wù)場景可能需要保存sql):
c.s.i.t.interceptor.ForbidInterceptor : row sql :
insert into employees (birth_date, first_name, last_name,gender, hire_date)
values ('2021-06-01 17:08:58', 'zhang', 'san',1, '2021-06-01 17:08:58')
基本功能實(shí)現(xiàn)了骄恶,來都來了食铐,順道看看Plugin的實(shí)現(xiàn)吧。
Mybatis中Plugin流程主要包括Plugin僧鲁、Interceptor虐呻、InterceptorChain三個核心類;其中Interceptor定義插件實(shí)際邏輯寞秃,然后Plugin使用JDK的動態(tài)代理對targetObject進(jìn)行代理(通常是Executor斟叼、PremeterHandler、StatementHandler春寿、ResultSetHandler的實(shí)現(xiàn))朗涩,最后在調(diào)用被代理對象方法時調(diào)用invoke(),執(zhí)行Interceptor邏輯绑改,所以可以把Plugin看作是wrapper+proxy谢床。InterceptorChain負(fù)責(zé)Interceptor的管理。使用Plugin通常需要實(shí)現(xiàn)org.apache.ibatis.plugin.Interceptor厘线,并重寫intercept()和plugin() (通常是Plugin.wrap(targe,this))萤悴。整個Plugin的執(zhí)行周期主要包括裝配和執(zhí)行兩部分,如下圖所示:
先來看Plugin的裝配皆的,可以分為兩步:將Interceptor加入InterceptorChain覆履、對targetObject進(jìn)行代理。InterceptorChain負(fù)責(zé)裝配Plugin费薄,裝配的總?cè)肟谠贑onfiguration硝全,先來看第一步
public class InterceptorChain {
// 全局Plugin
private final List<Interceptor> interceptors = new ArrayList<Interceptor>();
// 組裝所有plugin,最終結(jié)果是target的代理
public Object pluginAll(Object target) {
for (Interceptor interceptor : interceptors) {
// 核心楞抡,為target生成proxy伟众,同時封裝interceptor執(zhí)行邏輯
target = interceptor.plugin(target);
}
return target;
}
// 添加Interceptor
public void addInterceptor(Interceptor interceptor) {
interceptors.add(interceptor);
}
public List<Interceptor> getInterceptors() {
return Collections.unmodifiableList(interceptors);
}
XMLConfigBuilder(解析mybatis-config.xml)和Configuration都有Plugin裝配的入口,XMLConfigBuilder最終也是通過Configuration實(shí)現(xiàn)召廷。先來看XMLConfigBuilder
private void pluginElement(XNode parent) throws Exception {
if (parent != null) {
for (XNode child : parent.getChildren()) {
String interceptor = child.getStringAttribute("interceptor");
Properties properties = child.getChildrenAsProperties();
Interceptor interceptorInstance = (Interceptor) resolveClass(interceptor).newInstance();
interceptorInstance.setProperties(properties);
// 借助configuration實(shí)現(xiàn)plugin裝配
configuration.addInterceptor(interceptorInstance);
}
}
}
public void addInterceptor(Interceptor interceptor) {
interceptorChain.addInterceptor(interceptor);
}
下面這段Configuration中的邏輯可以解釋官網(wǎng)中對攔截點(diǎn)的說明(僅支持ParameterHandler凳厢、ResultSetHandler、StatementHandler竞慢、Executor)
// 創(chuàng)建ParameterHandler時先紫,為ParameterHandler裝配Plugins
public ParameterHandler newParameterHandler(MappedStatement mappedStatement, Object parameterObject, BoundSql boundSql) {
ParameterHandler parameterHandler = mappedStatement.getLang().createParameterHandler(mappedStatement, parameterObject, boundSql);
// 為ParameterHandler裝配Plugins
parameterHandler = (ParameterHandler) interceptorChain.pluginAll(parameterHandler);
return parameterHandler;
}
// 創(chuàng)建ResultSetHandler時,為ResultSetHandler裝配Plugins
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裝配Plugins
resultSetHandler = (ResultSetHandler) interceptorChain.pluginAll(resultSetHandler);
return resultSetHandler;
}
// 創(chuàng)建StatementHandler時筹煮,為StatementHandler裝配Plugins
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裝配Plugins
statementHandler = (StatementHandler) interceptorChain.pluginAll(statementHandler);
return statementHandler;
}
// 創(chuàng)建Executor時遮精,為Executor裝配Plugins
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裝配Plugins
executor = (Executor) interceptorChain.pluginAll(executor);
return executor;
}
此時所有Interceptor已經(jīng)全部加入到InterceptorChain,接著,對targetObject進(jìn)行層層代理本冲,核心邏輯如下:
public Object pluginAll(Object target) {
for (Interceptor interceptor : interceptors) {
// 核心准脂,為target生成proxy,同時封裝interceptor執(zhí)行邏輯
target = interceptor.plugin(target);
}
return target;
}
// 下面是Plugin類的核心邏輯
public static Object wrap(Object target, Interceptor interceptor) {
// @Intercepts注解處理
Map<Class<?>, Set<Method>> signatureMap = getSignatureMap(interceptor);
// 被代理類真實(shí)類型
Class<?> type = target.getClass();
Class<?>[] interfaces = getAllInterfaces(type, signatureMap);
// 生成接口的動態(tài)代理對象檬洞,注意這里只能是接口
if (interfaces.length > 0) {
return Proxy.newProxyInstance(
type.getClassLoader(),
interfaces,
new Plugin(target, interceptor, signatureMap));
}
return target;
}
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());
}
// 獲取注解內(nèi)Signature注解內(nèi)容至signatureMap狸膏,格式為<Class(攔截的接口),Set<Method>(攔截的接口方法集合)>,
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()) {
// 接口在signatureMap,則會生成代理類
if (signatureMap.containsKey(c)) {
interfaces.add(c);
}
}
type = type.getSuperclass();
}
return interfaces.toArray(new Class<?>[interfaces.size()]);
}
Plugin的執(zhí)行相對比較簡單添怔,因?yàn)镻lugin實(shí)現(xiàn)了JDK的InvocationHandler接口(invoke方法)湾戳,調(diào)用被代理類對象方法,會執(zhí)行Plugin的invoke()澎灸,邏輯如下;
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
try {
Set<Method> methods = signatureMap.get(method.getDeclaringClass());
// 當(dāng)前方法在被代理方法集合內(nèi)遮晚,執(zhí)行intercept邏輯
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);
}
}
這就是Mybatis中對Plugin的實(shí)現(xiàn)性昭,核心是通過JDK的動態(tài)代理對target進(jìn)行代理,并利用責(zé)任鏈模式對Plugin進(jìn)行裝配县遣。最后糜颠,歡迎指正。