public class JdkProxy implements InvocationHandler{
private Trancation2 trancation;
private Ihello target;
public JdkProxy(Trancation2 trancation, Ihello target) {
this.trancation = trancation;
this.target = target;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
// 开启事务
trancation.beginTrancation();
// 方法调用,注!!!此处传入的Object为代理,而不是目标类,目标类需要另外注入
Object obj = method.invoke(target, args);
// 开启事务
trancation.commit();
return obj;
}
}
// jdk的代理需要实现接口
interface Ihello{
void sayHello();
}
// 人员DAO
class IHeloImpl implements Ihello{
@Override
public void sayHello() {
System.out.println("保存人员");
}
}
// 事务
class Trancation2 {
public void beginTrancation() {
System.out.println("开启事务");
}
public void commit() {
System.out.println("提交事务");
}
}
// 客户端
class Client2 {
public static void main(String[] args) {
Trancation2 t2 = new Trancation2();
Ihello helo = new IHeloImpl();
JdkProxy jdkProxy = new JdkProxy(t2,helo);
Ihello helloProxy = (Ihello) Proxy.newProxyInstance(helo.getClass().getClassLoader(),helo.getClass().getInterfaces(),jdkProxy);
helloProxy.sayHello();
}
}
创建代理步骤
- 通过反射创建代理对象,并将Handler传给代理对象的构造方法
- 代理对象调用方法时,会调用Handler的方法
总结
-
相同的原理:
JDK代理和CGLIB代理的原理相似,都是通过编写代理的class文件,并将拦截的方法写入到代理的class中,在原有方法调用前,存在拦截器,则先调用拦截器的方法 -
JDK代理和CGLIB的区别:
JDK原生动态代理是Java原生支持的,不需要任何外部依赖,但是它只能基于接口进行代理;CGLIB通过继承的方式进行代理,无论目标对象有没有实现接口都可以代理,但是无法处理final的情况。