1 public class DefaultAopProxyFactory implements AopProxyFactory, Serializable { 2 3 @Override 4 public AopProxy createAopProxy(AdvisedSupport config) throws AopConfigException { 5 if (config.isOptimize() || config.isProxyTargetClass() || hasNoUserSuppliedProxyInterfaces(config)) { 6 Class<?> targetClass = config.getTargetClass(); 7 if (targetClass == null) { 8 throw new AopConfigException("TargetSource cannot determine target class: " + 9 "Either an interface or a target is required for proxy creation."); 10 } 11 if (targetClass.isInterface() || Proxy.isProxyClass(targetClass)) { 12 return new JdkDynamicAopProxy(config); 13 } 14 return new ObjenesisCglibAopProxy(config); 15 } 16 else { 17 return new JdkDynamicAopProxy(config); 18 } 19 } 20 21 /** 22 * Determine whether the supplied {@link AdvisedSupport} has only the 23 * {@link org.springframework.aop.SpringProxy} interface specified 24 * (or no proxy interfaces specified at all). 25 */ 26 private boolean hasNoUserSuppliedProxyInterfaces(AdvisedSupport config) { 27 Class<?>[] ifcs = config.getProxiedInterfaces(); 28 return (ifcs.length == 0 || (ifcs.length == 1 && SpringProxy.class.isAssignableFrom(ifcs[0]))); 29 } 30 31 }
spring 動態代理有jdk和Cglib兩種方式,具體選擇是在DefaultAopProxyFactory這個類裏面進行選擇的。spring
若是AOP使用顯式優化,或者配置了目標類,或者只使用Spring支持的代理接口執行第一個分支,不然使用JDK動態代理。第一個分支若是代理類是接口或者能夠被JDK動態代理使用JDK動態代理,不然使用CGLIB。ide