Spring 使用cglib技术创建代理还是基于标准jdk接口Proxy类呢?
我以为目标类实现了接口,那么使用标准jdk接口创建代理否则使用cglib。
其实不是!
Spring使用DefaultAopProxyFactory 创建代理
我们看 DefaultAopProxy类源码。
public class DefaultAopProxyFactory implements AopProxyFactory, Serializable {
@Override
public AopProxy createAopProxy(AdvisedSupport config) throws AopConfigException {
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) || ClassUtils.isLambdaClass(targetClass)) {
return new JdkDynamicAopProxy(config);
}
return new ObjenesisCglibAopProxy(config);
}
else {
return new JdkDynamicAopProxy(config);
}
}
}
由createAopProxy方法可知,是否使用cglib创建代理是由proxyTargetClass参数控制的。
当proxyTargetClass=true 采用cglib创建代理否则是Proxy。
Spring在创建代理时,不是简单地根据目标类是否实现接口来决定使用JDK动态代理还是cglib。实际决策过程由`DefaultAopProxyFactory`的`createAopProxy`方法控制,其中`proxyTargetClass`参数起关键作用。当`proxyTargetClass=true`时,使用cglib,否则使用JDK动态代理。如果目标类是接口或已知的代理类或Lambda,依然会使用JDK动态代理。
814

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



