前言
接前面一篇 dbflute的使用小结
项目上有这个需求 要拦截sql处理,否则每个功能点得重复处理。
想着看看这个框架有没有支持扩展拦截的,结果没有。所以考虑重写相关类。
解决方案-重写
找到org.dbflute.s2dao.sqlcommand这个包下的TnAbstractTwoWaySqlCommand.class类,拿出源码重写了当中的execute方法。代码如下:
public Object execute(Object[] args) {
final Node rootNode = getRootNode(args);
final CommandContext ctx = apply(rootNode, args, getArgNames(args), getArgTypes(args));
//代码重写
//final String executedSql = filterExecutedSql(ctx);
String executedSql = filterExecutedSql(ctx);
executedSql = DataAuthorSqlHandler.handlerSql(executedSql);
logger.debug("executedSql rewrite interceptor handlerSql:>>>>>>>>>>>>>" + executedSql);
//重写结束
final TnBasicParameterHandler handler = createBasicParameterHandler(ctx, executedSql);
final Object[] bindVariables = ctx.getBindVariables();
final Class<?>[] bindVariableTypes = ctx.getBindVariableTypes();
return filterReturnValue(handler.execute(bindVariables, bindVariableTypes));
}
这里示例,通过这种方式,在DataAuthorSqlHandler中开放了自定义的sql处理接口。
接前一篇测试实践,跑一下测试验证。
补充:dbflute 内部和外部sql处理最终执行入口都会经过这里。
总结
对与共同的逻辑处理,会考虑拦截或切面的方式去实现。
在处理中,首先考虑是否有对扩展开放的接入,类似plugin方式,没有的情况下,考虑局部重写。另外这也是技术选型的一个考量点。相比之下,开放支持业务会更灵活。