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。