spring boot 动态代理选择

 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这个类里面进行选择的。

如果AOP使用显式优化,或者配置了目标类,或者只使用Spring支持的代理接口执行第一个分支,否则使用JDK动态代理。第一个分支如果代理类是接口或者可以被JDK动态代理使用JDK动态代理,否则使用CGLIB。

posted @ 2019-03-19 14:26  Over_Watch  阅读(1719)  评论(0编辑  收藏  举报