jdk的动态代理也是mybatis的主要实现原理:
即动态生成dao层接口的实现类对象
代理的原理:不改变原对象的核心功能来做增强扩展
这里动态代理的实现条件:
1.原对象
2.公共接口
3.代理工厂
4.jdk工具接口
InvocationHandler
1.原对象:
package org.example.dynamic;
public class StudentService implements IStudentService {
@Override
public void add(){
// System.out.println(new Date() + "进入");
System.out.println("add student to db");
// System.out.println(new Date() + "退出");
}
@Override
public void find(){
System.out.println("find student from db");
}
}
2.公共接口:
package org.example.dynamic;
public interface IStudentService {
void add();
void find();
}
3.代理工厂
import java.util.Date;
@Data
public class LogInvocationHandler implements InvocationHandler {
private Object target;
// 增强时候执行的逻辑
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
String typeName = target.getClass().getName();
String methodName = method.getName();
// 增强
System.out.println(new Date() + " 进入 " + typeName+"."+methodName);
// 让原对象干
Object invoke = method.invoke(target, args);
System.out.println(new Date() + " 退出 " + typeName+"."+methodName);
return invoke;
}
}
测试类:
package org.example.dynamic;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;
public class Test01 {
// TARGET
IStudentService studentService = new StudentService();
LogInvocationHandler logHandler1 = new LogInvocationHandler();
logHandler1.setTarget(studentService);
// proxy
IStudentService studentServiceProxy = (IStudentService) Proxy.newProxyInstance(studentService.getClass().getClassLoader(),
new Class[]{IStudentService.class}, logHandler1);
studentService.add();
studentServiceProxy.find();
}
}
测试结果:
add student to db
Thu Aug 29 20:43:55 CST 2024 进入 org.example.dynamic.StudentService.find
find student from db
Thu Aug 29 20:43:55 CST 2024 退出 org.example.dynamic.StudentService.find