近期一个业务需要配置禁写,想通过Mybatis的Plugin来做,于是有了这篇文章。先来看官网对Plugin的介绍(以下内容来自官网)
// MyBatis 允许你在映射语句执行过程中的某一点进行拦截调用。默认情况下,MyBatis 允许使用插件来拦截的方法调用包括:
Executor (update, query, flushStatements, commit, rollback, getTransaction, close, isClosed)
ParameterHandler (getParameterObject, setParameters)
ResultSetHandler (handleResultSets, handleOutputParameters)
StatementHandler (prepare, parameterize, batch, update, query)
也就是说,在mybatis的执行流程中,支持Plugin的场景有且仅有:Executor、ParameterHandler、StatementHandler以及ResultSetHandler。针对我们的需求,刚开始打算直接从Executor入手,实现禁写并保存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,有点多此一举,不如直接切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();
}
//业务逻辑省略,这里仅打印执行sql,然后直接返回1,并不会真实执行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;
}
虽然可以实现禁写的目的,但是就像代码中注释的那样,有点多此一举;所以,直接来切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)){
// 省略业务逻辑,仅打印sql
String rawSql = ps.toString();
int updateIndex = rawSql.indexOf("update") == -1 ? rawSql.indexOf("insert") : -1;
// 非更新语句,直接执行
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;
}
结果也比较简单,可以看到具体待执行的sql(实际业务场景可能需要保存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')
基本功能实现了,来都来了,顺道看看Plugin的实现吧。
Mybatis中Plugin流程主要包括Plugin、Interceptor、InterceptorChain三个核心类;其中Interceptor定义插件实际逻辑,然后Plugin使用JDK的动态代理对targetObject进行代理(通常是Executor、PremeterHandler、StatementHandler、ResultSetHandler的实现),最后在调用被代理对象方法时调用invoke(),执行Interceptor逻辑,所以可以把Plugin看作是wrapper+proxy。InterceptorChain负责Interceptor的管理。使用Plugin通常需要实现org.apache.ibatis.plugin.Interceptor,并重写intercept()和plugin() (通常是Plugin.wrap(targe,this))。整个Plugin的执行周期主要包括装配和执行两部分,如下图所示:
先来看Plugin的装配,可以分为两步:将Interceptor加入InterceptorChain、对targetObject进行代理。InterceptorChain负责装配Plugin,装配的总入口在Configuration,先来看第一步
public class InterceptorChain {
// 全局Plugin
private final List<Interceptor> interceptors = new ArrayList<Interceptor>();
// 组装所有plugin,最终结果是target的代理
public Object pluginAll(Object target) {
for (Interceptor interceptor : interceptors) {
// 核心,为target生成proxy,同时封装interceptor执行逻辑
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实现。先来看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实现plugin装配
configuration.addInterceptor(interceptorInstance);
}
}
}
public void addInterceptor(Interceptor interceptor) {
interceptorChain.addInterceptor(interceptor);
}
下面这段Configuration中的逻辑可以解释官网中对拦截点的说明(仅支持ParameterHandler、ResultSetHandler、StatementHandler、Executor)
// 创建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;
}
// 创建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;
}
// 创建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;
}
// 创建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已经全部加入到InterceptorChain,接着,对targetObject进行层层代理,核心逻辑如下:
public Object pluginAll(Object target) {
for (Interceptor interceptor : interceptors) {
// 核心,为target生成proxy,同时封装interceptor执行逻辑
target = interceptor.plugin(target);
}
return target;
}
// 下面是Plugin类的核心逻辑
public static Object wrap(Object target, Interceptor interceptor) {
// @Intercepts注解处理
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;
}
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注解内容至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的执行相对比较简单,因为Plugin实现了JDK的InvocationHandler接口(invoke方法),调用被代理类对象方法,会执行Plugin的invoke(),逻辑如下;
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
try {
Set<Method> methods = signatureMap.get(method.getDeclaringClass());
// 当前方法在被代理方法集合内,执行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的实现,核心是通过JDK的动态代理对target进行代理,并利用责任链模式对Plugin进行装配。最后,欢迎指正。