转-AOP动态代理解析4-代理的创建

https://www.cnblogs.com/wade-luffy/p/6077277.html

做完了增强器的获取后就可以进行代理的创建了

AnnotationAwareAspectJAutoProxyCreator->postProcessAfterInitialization->wrapIfNecessary
protected Object wrapIfNecessary(Object bean, String beanName, Object cacheKey) {
    .....................
    // Create proxy if we have advice.
    Object[] specificInterceptors = getAdvicesAndAdvisorsForBean(bean.getClass(), beanName, null);
    if (specificInterceptors != DO_NOT_PROXY) {
        this.advisedBeans.put(cacheKey, Boolean.TRUE);
        Object proxy = createProxy(bean.getClass(), beanName, specificInterceptors, new SingletonTargetSource(bean));
        this.proxyTypes.put(cacheKey, proxy.getClass());
        return proxy;
    }
    ......................
}

代理获取分两个步骤:

  1. 增强器的封装
  2. 代理生成
protected Object createProxy(
        Class<?> beanClass, String beanName, Object[] specificInterceptors, TargetSource targetSource) {

    ProxyFactory proxyFactory = new ProxyFactory();
    //获取当前类中相关属性
    proxyFactory.copyFrom(this);
    //检查proxyTargeClass设置以及preserveTargetClass属性  
    //决定对于给定的bean是否应该使用targetClass而不是他的接口代理 
    if (!shouldProxyTargetClass(beanClass, beanName)) {
        // Must allow for introductions; can't just set interfaces to
        // the target's interfaces only.
        Class<?>[] targetInterfaces = ClassUtils.getAllInterfacesForClass(beanClass, this.proxyClassLoader);
        for (Class<?> targetInterface : targetInterfaces) {
            //添加代理接口
            proxyFactory.addInterface(targetInterface);
        }
    }
    //增强器的封装
   Advisor[] advisors = buildAdvisors(beanName, specificInterceptors);
    for (Advisor advisor : advisors) {
         //加入增强器 
        proxyFactory.addAdvisor(advisor);
    }
    //设置要代理的类 
    proxyFactory.setTargetSource(targetSource);
    //为子类提供了定制的函数customizeProxyFactory,子类可以在此函数中进行对ProxyFactory的进一步封装。
    customizeProxyFactory(proxyFactory);
    //缺省值为false即在代理被配置之后,不允许修改代理的配置。
    proxyFactory.setFrozen(this.freezeProxy);
    if (advisorsPreFiltered()) {
        proxyFactory.setPreFiltered(true);
    }

    return proxyFactory.getProxy(this.proxyClassLoader);
}

其中,封装Advisor并加入到ProxyFactory中以及创建代理是两个相对繁琐的过程,可以通过ProxyFactory提供的addAdvisor方法直接将增强器置入代理创建工厂中,但是将拦截器封装为增强器还是需要一定的逻辑的。

增强器的封装

protected Advisor[] buildAdvisors(String beanName, Object specificInterceptors[])  {  
    //解析注册的所有interceptorName  
    Advisor commonInterceptors[] = resolveInterceptorNames();  
    List allInterceptors = new ArrayList();  
    if(specificInterceptors != null)  
    {  
        //加入拦截器  
        allInterceptors.addAll(Arrays.asList(specificInterceptors));  
        if(commonInterceptors != null)  
            if(applyCommonInterceptorsFirst)  
                allInterceptors.addAll(0, Arrays.asList(commonInterceptors));  
            else  
                allInterceptors.addAll(Arrays.asList(commonInterceptors));  
    }  
    if(logger.isDebugEnabled())  
    {  
        int nrOfCommonInterceptors = commonInterceptors == null ? 0 : commonInterceptors.length;  
        int nrOfSpecificInterceptors = specificInterceptors == null ? 0 : specificInterceptors.length;  
        logger.debug((new StringBuilder())
          .append("Creating implicit proxy for bean '")
          .append(beanName).append("' with ").append(nrOfCommonInterceptors)
          .append(" common interceptors and ").append(nrOfSpecificInterceptors)
          .append(" specific interceptors").toString());  
    }  
    Advisor advisors[] = new Advisor[allInterceptors.size()];  
    for(int i = 0; i < allInterceptors.size(); i++)  
         //拦截器进行封装转化为Advisor  
         advisors[i] = advisorAdapterRegistry.wrap(allInterceptors.get(i));  
  
    return advisors;  
}  
public Advisor wrap(Object adviceObject) throws UnknownAdviceTypeException  {  
    //如果要封装的对象本身就是Advisor类型的那么无需做过多处理  
    if(adviceObject instanceof Advisor)  
        return (Advisor)adviceObject;  
    //因为此封装只对Advisor和Advice两种类型的数据有效,如果不是将不能封装  
    if(!(adviceObject instanceof Advice))  
        throw new UnknownAdviceTypeException(adviceObject);  
    Advice advice = (Advice)adviceObject;  
    if(advice instanceof MethodInterceptor)  
        //如果是MethodInterceptor类型则使用DefaultPointcutrAdvisor封装  
        return new DefaultPointcutAdvisor(advice);  
    //如果存在Advisor类型的适配器那么也同样需要进行封装  
    for(Iterator i$ = adapters.iterator(); i$.hasNext();)  
    {  
        AdvisorAdapter adapter = (AdvisorAdapter)i$.next();  
        if(adapter.supportsAdvice(advice))  
            return new DefaultPointcutAdvisor(advice);  
    }  
  
    throw new UnknownAdviceTypeException(advice);  
}  

由于Spring中涉及过多的拦截器,增强器,增强方法等方式来对逻辑进行增强,所以非常有必要统一封装成Advisor来进行代理的创建,完成了增强的封装过程,那么解析最终的一步就是代理的创建获取了。

代理生成

public Object getProxy(ClassLoader classLoader)  {  
    return createAopProxy().getProxy(classLoader);  //JdkDynamicAopProxy.getProxy()
} 
protected final synchronized AopProxy createAopProxy(){
     if(!active) activate();
         //创建代理  
        return getAopProxyFactory().createAopProxy(this);
 } 
public AopProxy createAopProxy(AdvisedSupport config) throws AopConfigException { 
    if(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())  
            return new JdkDynamicAopProxy(config);  
        else  
            return CglibProxyFactory.createCglibProxy(config);  
    } else  
    {  
        return new JdkDynamicAopProxy(config);  
    }  
}  

到此已经完成了代理的创建,现在从源代码的角度分析,看看到底Spring是如何选择代理方式的。
从if中的判断条件可以看到3个方面影响着spring的判断

  1. optimize:用来控制通过CGLIB创建的代理是否使用激进的优化策略。除非完全了解AOP代理是如何优化,否则不推荐用户使用这个设置,目前这个属性仅用于CGLIB代理,对于JDK动态代理(缺省代理)无效。
  2. proxyTargetClass:这个属性为true时,目标类本身被代理而不是目标类的接口。如果这个属性值被设为true,CGLIB代理将被创建。
  3. hasNOUser Supplied Proxy Interfaces:是否存在代理接口。

至此就是创建代理的过程,后面就是两种动态代理的生成proxy的方式和底层的实现。见Spring AOP 详解的jdk源码分析和cglib分析

下面是对JDK与Cglib方式的总结:

  1. 如果目标对象实现了接口,默认情况下会采用JDK的动态代理实现AOP。
  2. 如果目标对象实现了接口,可以强制使用CGLIB实现AOP。
  3. 如果目标对象没有实现了接口,必须采用CGLIB库。

Spring会自动在JDK动态代理和CGLIB之间转换。

如何强制使用CGLIB实现AOP?

  1. 添加CGLIB库,spring_home/cglib/*.jar。
  2. 在Spring配置文件中加入。

JDK动态代理和CGLIB字节码生成的区别?

  1. JDK动态代理只能对实现了接口的类生成代理,而不能针对类。
  2. CGLIB是针对类实现代理,主要是对指定的类生成一个子类,覆盖其中的方法,因为是继承,所以该类或方法最好不要声明成final。
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 157,298评论 4 360
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 66,701评论 1 290
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 107,078评论 0 237
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,687评论 0 202
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,018评论 3 286
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,410评论 1 211
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,729评论 2 310
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,412评论 0 194
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,124评论 1 239
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,379评论 2 242
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 31,903评论 1 257
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,268评论 2 251
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 32,894评论 3 233
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,014评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,770评论 0 192
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,435评论 2 269
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,312评论 2 260