Spring之CGLIB和JDK动态代理底层实现
目录
Spring会自动在JDK动态代理和CGLIB之间转换:
1、如果目标对象实现了接口,默认情况下会采用JDK的动态代理实现AOP
2、如果目标对象实现了接口,可以强制使用CGLIB实现AOP
3、如果目标对象没有实现了接口,必须采用CGLIB库
本文主要讲解CGLIB和JDK动态代理的使用和底层原理,以及Spring如何自动在JDK动态代理和CGLIB之间转换
CGLIB
CGLIB动态代理是利用ASM开源包,对代理对象类的class文件加载进来,通过修改其字节码生成子类来处理。
使用示例-支持创建代理对象,执行代理逻辑
新建一个UserService类,这个类是目标类,后续会被代理
public class UserService {
public void test() {
System.out.println("userService execute test....");
}
}
使用Enhancer类设置代理类UserService,设置代理逻辑,创建代理对象
public class CylTest {
public static void main(String[] args) {
UserService target = new UserService();
Enhancer enhancer = new Enhancer();
enhancer.setSuperclass(UserService.class);
//设置代理逻辑
enhancer.setCallbacks(new Callback[]{new MethodInterceptor() {
@Override
public Object intercept(/*目标对象*/Object o,
/*目标对象方法*/Method method,
/*参数*/Object[] args,
/*代理对象方法*/MethodProxy methodProxy)
throws Throwable {
System.out.println("before");
Object result = method.invoke(target, args);
System.out.println("after");
return result;
}
}});
//创建代理对象=>类型是UserService,但却是代理对象
UserService userService = (UserService) enhancer.create();
userService.test();
}
}
这个阶段会产生三个对象:
1.目标对象-targetUserService
2.负责创建代理对象的工厂对象enhancer
3.代理对象-proxyUserService
最终执行效果:
before
userService execute test....
after
使用示例-多个方法,走不同的代理逻辑
新建一个UserService类,设置两个方法
public void test() {
System.out.println("userService execute test....");
}
public void a() {
System.out.println("userService execute a....");
}
在enhancer对象中设置两个代理逻辑,test方法走代理逻辑1,a方法走代理逻辑2
public static void main(String[] args) {
UserService targetUserService = new UserService();
Enhancer enhancer = new Enhancer();
enhancer.setSuperclass(UserService.class);
//代理逻辑:1
MethodInterceptor firstCallback = new MethodInterceptor() {
@Override
public Object intercept(Object o, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
System.out.println("before");
Object result = method.invoke(targetUserService, args);
System.out.println("after");
return result;
}
};
//代理逻辑:2
NoOp secondCallback = NoOp.INSTANCE;
enhancer.setCallbacks(new Callback[]{firstCallback, secondCallback});
enhancer.setCallbackFilter(new CallbackFilter() {
@Override
public int accept(Method method) {
//方法test执行=》firstCallback代理逻辑:1
if (method.getName().equals("test")) {
return 0;
}
//其他执行=》secondCallback代理逻辑:2
return 1;
}
});
UserService proxyUserService = (UserService) enhancer.create();
System.out.println("执行proxyUserService.test:");
proxyUserService.test();
System.out.println("--------------------------------------------------------");
System.out.println("执行proxyUserService.a:");
proxyUserService.a();
}
最终执行效果:
执行proxyUserService.test:
before
userService execute test....
after
--------------------------------------------------------
执行proxyUserService.a:
userService execute a....
JDK动态代理
JDK动态代理是利用反射机制生成一个实现代理接口的匿名类,在调用具体方法前调用InvokeHandler来处理。
使用示例-支持创建代理对象,执行代理逻辑
//接口
public interface UserInterface {
void test();
void a();
}
//实现类
public class UserService implements UserInterface {
@Override
public void test() {
System.out.println("userService execute test....");
}
@Override
public void a() {
System.out.println("userService execute a....");
}
}
使用Proxy.newProxyInstance创建一个代理接口,InvocationHandler制定代理逻辑
public class CylTest {
public static void main(String[] args) {
UserService targetUserService = new UserService();
UserInterface proxyUserInterface = (UserInterface) Proxy.newProxyInstance(
UserInterface.class.getClassLoader(),
new Class[]{UserInterface.class},
new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("before");
Object result = method.invoke(targetUserService, args);
System.out.println("after");
return result;
}
});
proxyUserInterface.test();
}
}
最终执行效果:
before
userService execute test....
after
ProxyFactory
如何自动在CGLIB和JDK动态代理转换
ProxyFactory是Spring封装的代理工厂,对目标对象使用CGLIB或者JDK动态代理有处理逻辑。
代理方式 | |
CGLIB | isProxyTargetClass属性=true |
只实现了SpringProxy接口 | |
被代理对象没有实现接口 | |
JDK动态代理 | 被代理类只实现了接口,且实现了非SpringProxy接口 |
org.springframework.aop.framework.DefaultAopProxyFactory#createAopProxy
@Override
public AopProxy createAopProxy(AdvisedSupport config) throws AopConfigException {
// 如果ProxyFactory的isOptimize为true,Spring认为cglib比jdk动态代理要快
// 或者isProxyTargetClass为true,
// 或者被代理对象没有实现接口,
// 或者只实现了SpringProxy这个接口
// 那么则利用Cglib进行动态代理,但如果被代理类是接口,或者被代理类已经是进行过JDK动态代理而生成的代理类了则只能进行JDK动态代理
// 其他情况都会进行JDK动态代理,比如被代理类实现了除SpringProxy接口之外的其他接口
// 是不是在GraalVM虚拟机上运行
if (!NativeDetector.inNativeImage() &&
(config.isOptimize() || config.isProxyTargetClass() || hasNoUserSuppliedProxyInterfaces(config))) {
Class<?> targetClass = config.getTargetClass();
if (targetClass == null) {
throw new AopConfigException("TargetSource cannot determine target class: " +
"Either an interface or a target is required for proxy creation.");
}
if (targetClass.isInterface() || Proxy.isProxyClass(targetClass)) {
return new JdkDynamicAopProxy(config);
}
return new ObjenesisCglibAopProxy(config);
}
else {
return new JdkDynamicAopProxy(config);
}
}
使用示例-使用CGLIB代理方式
设置目标类
public class UserService {
public void test() {
System.out.println("test...");
}
}
public static void main(String[] args) {
UserService userService = new UserService();
ProxyFactory proxyFactory = new ProxyFactory();
//
proxyFactory.setTarget(userService);
//代理逻辑1
MethodBeforeAdvice methodBeforeAdvice = new MethodBeforeAdvice() {
@Override
public void before(Method method, Object[] args, Object target) throws Throwable {
System.out.println("begin");
}
};
//代理逻辑2
AfterReturningAdvice afterReturningAdvice = new AfterReturningAdvice() {
@Override
public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
System.out.println("end");
}
};
//添加多个代理逻辑
proxyFactory.addAdvice(0, methodBeforeAdvice);
proxyFactory.addAdvice(1, afterReturningAdvice);
UserService proxyUserService = (UserService) proxyFactory.getProxy();
proxyUserService.test();
}
使用示例-使用JDK动态代理方式
设置目标接口
//UserInterface
public interface UserInterface {
void test();
}
//UserService
public class UserService implements UserInterface {
@Override
public void test() {
System.out.println("test...");
}
}
public static void main(String[] args) {
UserService userService = new UserService();
ProxyFactory proxyFactory = new ProxyFactory();
proxyFactory.setTarget(userService);
proxyFactory.setInterfaces(UserInterface.class);
//代理逻辑1
MethodBeforeAdvice methodBeforeAdvice = new MethodBeforeAdvice() {
@Override
public void before(Method method, Object[] args, Object target) throws Throwable {
System.out.println("begin");
}
};
//代理逻辑2
AfterReturningAdvice afterReturningAdvice = new AfterReturningAdvice() {
@Override
public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
System.out.println("end");
}
};
//添加多个代理逻辑
proxyFactory.addAdvice(0, methodBeforeAdvice);
proxyFactory.addAdvice(1, afterReturningAdvice);
UserInterface proxyUserService = (UserInterface) proxyFactory.getProxy();
proxyUserService.test();
}
原文地址:https://blog.csdn.net/changyinling520/article/details/137893727
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!