springAOP的动态代理的原理

 

 

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 2022-07-25 21:45  小北呦  阅读(51)  评论(0)    收藏  举报