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代理区别](https://img.it610.com/image/info8/6e5a8beb97c5465b982511fd8e3e9797.jpg)
文章图片
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代理区别](https://img.it610.com/image/info8/15f2d3a654a14ec9ae81dc830e459e43.jpg)
文章图片
项目如下:
![Spring|Spring之AOP——详述JDK代理与CGLib代理区别](https://img.it610.com/image/info8/b4bde1f534934540b287ae56c272d10d.jpg)
文章图片
![Spring|Spring之AOP——详述JDK代理与CGLib代理区别](https://img.it610.com/image/info8/bc901fcc06994dfdae51d08a27866aeb.jpg)
文章图片
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;
}
}
推荐阅读
- PMSJ寻平面设计师之现代(Hyundai)
- 太平之莲
- 闲杂“细雨”
- 七年之痒之后
- 深入理解Go之generate
- 由浅入深理解AOP
- Activiti(一)SpringBoot2集成Activiti6
- 期刊|期刊 | 国内核心期刊之(北大核心)
- 生活随笔|好天气下的意外之喜
- 感恩之旅第75天