1、Jdk动态代理实例:JDK动态代理只能代理实现了接口的类,其他普通类不能实现。代理类会在newProxyInstance方法中生成
接口:
package proxy.jdk;public interface BookFacade {
public void addBook();
public void deleteBook();
}
业务实现类:
package proxy.jdk;
public class BookFacadeImpl implements BookFacade{
@Override
public void addBook() {
System.out.println("addBook...");
}
@Override
public void deleteBook() {
System.out.println("deleteBook...");
}
}
动态代理类:
package proxy.jdk;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class BookFacadeProxy implements InvocationHandler {
private Object target;
public BookFacadeProxy(){}
public Object bind(Object target){
this.target = target;
return Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(), this);
}
@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
System.out.println("before proxy...");
method.invoke(target, args);
System.out.println("after proxy...");
return null;
}
}
测试:
package proxy.jdk;
public class TestJdkProxy {
/**
* @param args
*/
public static void main(String[] args) {
BookFacadeProxy proxy = new BookFacadeProxy();
BookFacade book = (BookFacade)proxy.bind(new BookFacadeImpl());
System.out.println(book.getClass().getSimpleName());
book.addBook();
book.deleteBook();
}
}
结果:
$Proxy0
before proxy...
addBook...
after proxy...
before proxy...
deleteBook...
after proxy...
2、cglib动态代理:cglib是针对类实现代理的,为代理的类生成一个子类,覆盖方法实现增强,因为采用的是继承所以不能代理final修饰的类。需要cglib和asm两个jar包
需要代理的类:
package proxy.cglib;
public class BookFacadeImpl {
public void addBook() {
System.out.println("addBook...");
}
public void deleteBook() {
System.out.println("deleteBook...");
}
}
cglib动态代理类:
package proxy.cglib;
import java.lang.reflect.Method;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
/**
* 使用cglib动态代理
*
* @author student
*
*/
public class BookFacadeCglib implements MethodInterceptor {
private Object target;
/**
* 创建代理对象
*
* @param target
* @return
*/
public Object getInstance(Object target) {
this.target = target;
Enhancer enhancer = new Enhancer();
enhancer.setSuperclass(this.target.getClass());
// 回调方法
enhancer.setCallback(this);
// 创建代理对象
return enhancer.create();
}
@Override
// 回调方法
public Object intercept(Object obj, Method method, Object[] args,
MethodProxy proxy) throws Throwable {
System.out.println("事物开始");
proxy.invokeSuper(obj, args);
System.out.println("事物结束");
return null;
}
}
测试:
package proxy.cglib;
public class TestCglibProxy {
/**
* @param args
*/
public static void main(String[] args) {
BookFacadeCglib cglib=new BookFacadeCglib();
BookFacadeImpl bookCglib=(BookFacadeImpl)cglib.getInstance(new BookFacadeImpl());
bookCglib.addBook();
}
}
结果:
事物开始
addBook...
事物结束