ibatis-2中,在MappedStatement.java类中的executeQueryWithCallback()方法统一处理查询操作,在此注入自定义逻辑即可。
ibatis-3,即改名为mybatis后,提供了 org.apache.ibatis.plugin.Interceptor 可以实现相关功能。
1. Java Agent
我们编写一个代理jar,这个jar包通过JVMTI(JVM Tool Interface)完成加载,最终借助JPLISAgent(Java Programming Language Instrumentation Services Agent)完成对目标代码的修改。
Java Agent支持目标JVM启动时加载,也支持在目标JVM运行时加载,这两种不同的加载模式会使用不同的入口函数。
如果需要在目标JVM启动的同时加载Agent,那么可以选择实现下面的方法:
[1] public static void premain(String agentArgs, Instrumentation inst);
[2] public static void premain(String agentArgs);
JVM将首先寻找[1],如果没有发现[1],再寻找[2]。
如果希望在目标JVM运行时加载Agent,则需要实现下面的方法:
[1] public static void agentmain(String agentArgs, Instrumentation inst);
[2] public static void agentmain(String agentArgs);
2. Javassist
Javassist(Java Programming Assistant) makes Java bytecode manipulation simple. It is a class library for editing bytecodes in Java; it enables Java programs to define a new class at runtime and to modify a class file when the JVM loads it. Unlike other similar bytecode editors, Javassist provides two levels of API: source level and bytecode level. If the users use the source-level API, they can edit a class file without knowledge of the specifications of the Java bytecode. The whole API is designed with only the vocabulary of the Java language. You can even specify inserted bytecode in the form of source text; Javassist compiles it on the fly. On the other hand, the bytecode-level API allows the users to directly edit a class file as other editors.
简而言之,javassist可以用来在JVM加载类时编辑字节码。
3. 动态修改方法
3.1 实现
public class IbatisAgent {
private static Instrumentation inst = null;
public static void premain(String agentArgs, Instrumentation _inst){
System.out.println("IbatisAgent.premian() was called.");
inst = _inst;
// 具体实现修改字节码的处理类
ClassFileTransformer trans = new IbatisTransform();
System.out.println("Adding a Ibatis Agent instance to the JVM.");
inst.addTransformer(trans);
}
}
public class IbatisTransform implements ClassFileTransformer {
private static final String TARGET_CLASS = "com/ibatis/sqlmap/engine/mapping/statement/MappedStatement";
// 通过-Dibatis_jar_path=/home/pay/xxxx.jar设置ibatis包路径
private static final String IBATIS_JAR_PATH = System.getProperty("ibatis.jar.path","");
private static final String APP_JAR_PATH = System.getProperty("app.jar.path","");
@Override
public byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) {
// 过滤类,只处理指定的类
if(!TARGET_CLASS.equals(className)){
// 返回null,表示不对类做修改
return null;
}
byte[] transformed = null;
CtClass cl = null;
try {
ClassPool pool = ClassPool.getDefault();
// 添加classpath
pool.appendClassPath(APP_JAR_PATH);
pool.appendClassPath(IBATIS_JAR_PATH);
// 引入依赖包
pool.importPackage("java.util.regex.Matcher");
pool.importPackage("java.util.regex.Pattern");
pool.importPackage("java.util.Arrays");
pool.importPackage("com.ibatis.sqlmap.engine.mapping.statement.RowHandlerCallback");
pool.importPackage("java.sql.SQLException");
pool.importPackage("com.ibatis.common.jdbc.exception.NestedSQLException");
pool.importPackage("com.ibatis.sqlmap.engine.scope.StatementScope");
pool.importPackage("java.text.SimpleDateFormat");
cl = pool.makeClass(new ByteArrayInputStream(classfileBuffer));
if(!cl.isInterface()) {
System.out.println("agent working ----------------------------------------------> " + className);
CtBehavior[] methods = cl.getDeclaredBehaviors();
for (CtBehavior method : methods) {
doMethod(method);
}
transformed = cl.toBytecode();
}
} catch (Exception e) {
e.printStackTrace();
}finally {
if(cl != null){
cl.detach();
}
}
return transformed;
}
private void doMethod(CtBehavior method) throws NotFoundException, CannotCompileException {
if("executeQueryWithCallback".equalsIgnoreCase(method.getName())){
//开始对方法进行修改,这里替换了整个方法实现
String mbody = "{com.ibatis.sqlmap.engine.scope.ErrorContext errorContext = $1.getErrorContext();\n"
+ " errorContext.setActivity(\"preparing the mapped statement for execution\");\n"
+ " errorContext.setObjectId(this.getId());\n"
+ " errorContext.setResource(this.getResource());\n"
+ " try {\n"
+ " $3 = this.validateParameter($3);\n"
+ " com.ibatis.sqlmap.engine.mapping.sql.Sql sql = this.getSql();\n"
+ " errorContext.setMoreInfo(\"Check the parameter map.\");\n"
+ " final com.ibatis.sqlmap.engine.mapping.parameter.ParameterMap parameterMap = sql.getParameterMap($1, $3);\n"
+ " errorContext.setMoreInfo(\"Check the result map.\");\n"
+ " final com.ibatis.sqlmap.engine.mapping.result.ResultMap resultMap = sql.getResultMap($1, $3);\n"
+ " $1.setResultMap(resultMap);\n"
+ " $1.setParameterMap(parameterMap);\n"
+ " errorContext.setMoreInfo(\"Check the parameter map.\");\n"
+ " Object[] parameters = parameterMap.getParameterObjectValues($1, $3);\n"
+ " // ⚠️在此处,可以对parameters进行过滤处理。由于场景不同,此处不给出具体处理办法。\n"
+ " // ⚠️数组里的对象类型不同,可以用instanceof判断后处理。\n"
+ " errorContext.setMoreInfo(\"Check the SQL statement.\");\n"
+ " final String sqlString = sql.getSql($1, $3);\n"
+ " //System.out.println(\"sqlString-->\" + sqlString + \" , \" + java.util.Arrays.toString(parameters));\n"
+ " errorContext.setActivity(\"executing mapped statement\");\n"
+ " errorContext.setMoreInfo(\"Check the SQL statement or the result map.\");\n"
+ " final com.ibatis.sqlmap.engine.mapping.statement.RowHandlerCallback callback = new RowHandlerCallback(resultMap, $4, $5);\n"
+ " this.sqlExecuteQuery($1, $2, sqlString, parameters, $6, $7, callback);\n"
+ " errorContext.setMoreInfo(\"Check the output parameters.\");\n"
+ " if ($3 != null) {\n"
+ " this.postProcessParameterObject($1, $3, parameters);\n"
+ " }\n"
+ " errorContext.reset();\n"
+ " sql.cleanup($1);\n"
+ " this.notifyListeners();\n"
+ " }\n"
+ " catch (SQLException e) {\n"
+ " errorContext.setCause(e);\n"
+ " throw new NestedSQLException(errorContext.toString(), e.getSQLState(), e.getErrorCode(), e);\n"
+ " }\n"
+ " catch (Exception e2) {\n"
+ " errorContext.setCause(e2);\n"
+ " throw new NestedSQLException(errorContext.toString(), e2);\n"
+ " }}";
method.setBody(mbody);
}
}
}
3.2 打包
以idea为例
image.png- 打开Project Settings,点击Artifacts;
- 点击“+”, 创建jar;
- 将jar关联manifest文件;
- 选择将manifest文件存放在resources目录下,方便后续修改;
点击“OK”完成。
修改 MANIFEST.MF 文件,如下:
Manifest-Version: 1.0
Main-Class:
Class-Path: javassist-3.20.0-GA.jar
// ⚠️添加一下两项配置
Premain-Class: com.xxxx.agent.ibatis.IbatisAgent
Can-Redefine-Classes: true
3.3 执行
以linux下tomcat为例,将java agentjar包和javassist依赖jar包放在tomcat/lib目录下。
执行 “vi bin/catalina.sh ”,添加配置如下:
# ----- Execute The Requested Command -----------------------------------------
JAVA_OPTS="$JAVA_OPTS -Dibatis.jar.path=/home/user/tomcat/webapps/app/WEB-INF/lib/ibatis-2.3.4.726.jar -Dapp.jar.path=/home/user/tomcat/webapps/app/WEB-INF/classes -javaagent:/home/user/tomcat/lib/ibatisagent.jar"
运行项目即可。
4. javassist 注意要点
4.1 方法参数
例如:
public void plus(int a, int b){
return a+b;
}
我们要在在方法里面引用参数a和b,需要使用 $1, $2,序号即位方法参数的序号。
4.2 对象声明
在类中声明变量,需要带上包名,即 “包名.类名”,例如:
com.ibatis.sqlmap.engine.mapping.statement.RowHandlerCallback callback = new RowHandlerCallback(resultMap, $4, $5);
4.3 访问静态参数或方法
例如我们项目中有一个静态变量:
package com.xxxx.app;
public class Constants {
public static String flag;
}
在方法中如果想引用Constants,如下:
com.xxxx.app.Constants#flag = "ok";
⚠️需要用#号替代⚠️
网友评论