JDK 的基于接口的动态代理: 实现同一接口 利用proxy 和 newProxyInstance , invoke 实现
========MyJdkProxy========
public class MyJdkProxy implements InvocationHandler{
private UserDao userDao;
public MyJdkProxy(UserDao userDao){
this.userDao = userDao;
}
public Object createProxy(){
Object proxy = Proxy.newProxyInstance(userDao.getClass().getClassLoader(),userDao.getClass().getInterfaces(),this);
return proxy;
}
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if("save".equals(method.getName())){
System.out.println("权限校验...");
return method.invoke(userDao,args);
}
return method.invoke(userDao,args);
}
CGLIB生成的动态代理: 继承这个目标类生成一个子类
通过 Enhancer实现 setSuperclass(对应类) enhancer.create()实现
========MyCglibPorxy========
public class MyCglibPorxy implements MethodInterceptor {
private ProdectDao prodectDao;
public MyCglibPorxy(ProdectDao prodectDao){
this.prodectDao=prodectDao;
}
public Object createProxy(){
//1.创建核心类
Enhancer enhancer = new Enhancer();
//2.设置父类
enhancer.setSuperclass(prodectDao.getClass());
//3.设置回调
enhancer.setCallback(this);
//4.生成代理
Object proxy = enhancer.create();
return proxy;
}


posted on
浙公网安备 33010602011771号