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文件
<context:component-scan base-package="com.jd"></context:component-scan>
<bean id="ma" class="com.jd.aop.MethodAOP"/>
<aop:config proxy-target-class="false">
<!-- proxy-target-class默认为falseproxy-target-class属性值决定是基于接口的还是基于类的代理被创建。
为true则是基于类的代理将起作用(需要cglib库),为false(默认),则标准的JDK 基于接口的代理将起作用。-->
<!-- aop:pointcut用于定义一个aop表达式 -->
<aop:pointcut expression="execution(public int com.jd.computer.service.ComputerService.*(..))" id="pc"/>
<!-- aop:aspect用于设置一个切面类 -->
<aop:aspect ref="ma">
<aop:before method="before" pointcut-ref="pc"/>
</aop:aspect>
</aop:config>
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();
}
}
<context:component-scan base-package="com.jd"></context:component-scan>
<bean id="ma" class="com.jd.aop.MethodAOP"/>
<aop:config proxy-target-class="true">
<aop:pointcut expression="execution(public int com.jd.computer.service.ComputerService.*(..))" id="pc"/>
<aop:aspect ref="ma">
<aop:before method="before" pointcut-ref="pc"/>
</aop:aspect>
</aop:config>
项目如下:
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;
}
}