jdk動態代理和cglib動態代理的區別
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...
事物結束