//JDK动态代理基于接口实现,所以实现JDK动态代理,必须先定义接口JDK代理与目标类没有关系
配置如下:
application.xml文件中
<aop:aspectj-autoproxy proxy-target-class="false"/>
Test:
package com.jd.test;
import org.springframework.cglib.core.DebuggingClassWriter;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.jd.calculator.IUserInfoService;
public class Test {
public static void main(String[] args) {
ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("application.xml");
ICalculatorService calculatorService =applicationContext.getBean(IUserInfoService.class);//不能写UserInfo.class
Class clazz = calculatorService.getClass();
System.out.println(clazz.getName());
applicationContext.close();
}
}
//CGLIB代理类继承目标类
application.xml文件中
<aop:aspectj-autoproxy proxy-target-class="true"/>
Test:
package com.jd.test;
import org.springframework.cglib.core.DebuggingClassWriter;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.jd.calculator.IUserInfoService;
public class Test {
public static void main(String[] args) {
ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("application.xml");
ICalculatorService calculatorService =applicationContext.getBean(UserInfoService.class);//因为代理类继承了目标类即可以调用实现接口
Class clazz = calculatorService.getClass();
System.out.println(clazz.getName());
applicationContext.close();
}
}
本文详细解析了JDK动态代理和CGLIB动态代理的实现原理及配置方式,通过具体代码示例展示了如何在Spring框架下使用这两种代理机制。JDK动态代理基于接口实现,适用于实现了接口的目标类;而CGLIB代理则通过继承目标类来创建代理对象,适用于没有实现接口的类。
962

被折叠的 条评论
为什么被折叠?



