代理分为两种:
1.静态代理
2.动态代理
动态代理又分为两种:jdk 实现 ;Cglib 实现
3.Java中如何实现代理机制(JDK、CGLIB)
JDK动态代理:代理类和目标类实现了共同的接口,用到InvocationHandler接口。
CGLIB动态代理:代理类是目标类的子类,用到MethodInterceptor接口。
注意:
使用版本:
首先介绍jdk 实现动态代理:
第一步:建立接口
package com.asiainfo.proxydemo;
public interface BookFacade {
public void addBook();
}
第二步:实现接口
package com.asiainfo.proxydemo;
import java.io.Serializable;
public class BookFacadeImpl implements BookFacade, Serializable {
public void addBook() {
// TODO Auto-generated method stub
System.out.println("增加图书方法。。。");
}
}
第三步:建立代理类
package com.asiainfo.proxydemo;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class BookFacadeProxy implements InvocationHandler {
private Object target;
public Object bind(Object target){
this.target=target;
return Proxy.newProxyInstance(target.getClass().getClassLoader(), (Class<?>[]) target.getClass().getGenericInterfaces(), this);
}
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
// TODO Auto-generated method stub
Object result=null;
System.out.println("事物开始执行");
method.invoke(target, args);
System.out.println("事情结束");
return null;
}
//代码测试
public static void main(String[] args) {
BookFacade target = new BookFacadeImpl();
BookFacade bookFacadeProxy = (BookFacade) new BookFacadeProxy().bind(target);
bookFacadeProxy.addBook();
}
}
其次是Cglib 实现:
第一步:
package com.asiainfo.proxydemo;
public class BookFacadeCglib {
public void addBook(){
System.out.println("addBook");
}
}
第二步:cglib 建立测试类
package com.asiainfo.proxydemo;
import java.lang.reflect.Method;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
public class BookFacadeProxyCglib implements MethodInterceptor {
private Object target;
public Object getInstance(Object target){
this.target=target;
Enhancer enhancer=new Enhancer();
enhancer.setSuperclass(this.target.getClass());
//回调方法
//enhancer.setCallbackType(this.target.getClass());
enhancer.setCallback(this);
//创建代理对象
return enhancer.create();
}
public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
// TODO Auto-generated method stub
System.out.println("before run");
Object returnvalue=proxy.invokeSuper(obj, args);
System.out.println("after run");
return null;
}
//cglib代码测试
public static void main(String[] args) {
BookFacadeCglib target = new BookFacadeCglib();
BookFacadeCglib bookFacadeCglib = (BookFacadeCglib) new BookFacadeProxyCglib().getInstance(target);
bookFacadeCglib.addBook();
}
}
参考:http://lrd.ele.me/2017/01/09/dynamic_proxy/
:https://blog.csdn.net/einstein10147/article/details/77040110