Spring|Spring之AOP——详述JDK代理与CGLib代理区别

JDK动态代理与CGLib动态代理区别:
【Spring|Spring之AOP——详述JDK代理与CGLib代理区别】1、JDK动态代理基于接口实现,所以实现JDK动态代理,必须先定义接口;CGLib动态代理基于被代理类实现;
2、JDK动态代理机制是委托机制,委托hanlder调用原始实现类方法;CGLib则使用继承机制,被代理类和代理类是继承关系,所以代理类对象可以赋值给被代理类类型的变量;如果被代理类有接口,那么代理类对象也可以赋值给该接口类型的变量。
JDK动态代理

public class Test { public static void main(String[] args) { ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("application.xml"); IComputerService computerService = applicationContext.getBean(IComputerService.class); Class clazz= computerService.getClass(); //proxy-target-class="false" //JDK:代理类和目标类没有继承关系,代理类实现了目标类所实现的接口 for (Class c : clazz.getInterfaces()) { System.out.println(c.getName()); }applicationContext.close(); }}

xml文件


Spring|Spring之AOP——详述JDK代理与CGLib代理区别
文章图片

CGLib动态代理
public class Test { public static void main(String[] args) { ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("application.xml"); IComputerService computerService = applicationContext.getBean(IComputerService.class); Class clazz= computerService.getClass(); //proxy-target-class="true" //CGLib代理 //代理类继承自目标类 System.out.println(clazz.getSuperclass().getName()); applicationContext.close(); }}



Spring|Spring之AOP——详述JDK代理与CGLib代理区别
文章图片


项目如下:
Spring|Spring之AOP——详述JDK代理与CGLib代理区别
文章图片
Spring|Spring之AOP——详述JDK代理与CGLib代理区别
文章图片


public class MethodAOP { public void before(JoinPoint jp) { Object [] agrs = jp.getArgs(); Signature signature = jp.getSignature(); String name = signature.getName(); System.out.println("The "+name+" method begins."); System.out.println("The div method params["+agrs[0]+","+agrs[1]+"]"); } }


@Service public class ComputerService implements IComputerService { public int div(int a, int b) { return a/b; } }





    推荐阅读