SPRING源碼學習之路(三)——自動代理的實現


        關於Spring AOP的基本概念這裏不作闡述,重點關心autoProxy


        對於<aop:config>標籤的解析,對應的類 AopNamespaceHandler,ConfigBeanDefinitionParser


        ConfigBeanDefinitionParser核心方法parse的具體實現如下:

public BeanDefinition parse(Element element, ParserContext parserContext) {
        CompositeComponentDefinition compositeDef = new CompositeComponentDefinition(element.getTagName(), parserContext.extractSource(element));
        parserContext.pushContainingComponent(compositeDef);
        this.configureAutoProxyCreator(parserContext, element);
        List childElts = DomUtils.getChildElements(element);
        Iterator i$ = childElts.iterator();

        while(i$.hasNext()) {
            Element elt = (Element)i$.next();
            String localName = parserContext.getDelegate().getLocalName(elt);
            if("pointcut".equals(localName)) {
                this.parsePointcut(elt, parserContext);
            } else if("advisor".equals(localName)) {
                this.parseAdvisor(elt, parserContext);
            } else if("aspect".equals(localName)) {
                this.parseAspect(elt, parserContext);
            }
        }

        parserContext.popAndRegisterContainingComponent();
        return null;
    }

    其中 

this.configureAutoProxyCreator(parserContext, element);
        這行代碼  會創建AspectJAwareAdvisorAutoProxyCreator類 並向容器註冊

        從名字就可以看出,這個類是自帶代理實現的核心類,繼承關係圖:

       

實現了BeanPostProcessor,BeanFactoryAware接口,這下就有意思了,即可以通過容器獲取bean信息,也可以在bean初始化時候增強處理


那到底該類是如何實現對需要的類實現自動代理的呢,在祖父類AbstractAutoProxyCreator中可以看到 對BeanPostProcessor接口的實現 postProcessBeforeInstantiation方法

public Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) throws BeansException {
        Object cacheKey = this.getCacheKey(beanClass, beanName);
        if(beanName == null || !this.targetSourcedBeans.containsKey(beanName)) {
            if(this.advisedBeans.containsKey(cacheKey)) {
                return null;
            }

            if(this.isInfrastructureClass(beanClass) || this.shouldSkip(beanClass, beanName)) {
                this.advisedBeans.put(cacheKey, Boolean.FALSE);
                return null;
            }
        }

        if(beanName != null) {
            TargetSource targetSource = this.getCustomTargetSource(beanClass, beanName);
            if(targetSource != null) {
                this.targetSourcedBeans.put(beanName, Boolean.TRUE);
                //獲取advice和advisor
               Object[] specificInterceptors = this.getAdvicesAndAdvisorsForBean(beanClass, beanName, targetSource);
                Object proxy = this.createProxy(beanClass, beanName, specificInterceptors, targetSource);
                this.proxyTypes.put(cacheKey, proxy.getClass());
                return proxy;
            }
        }

        return null;
    }

getAdvicesAndAdvisorsForBean方法的實現具體如下:

protected Object[] getAdvicesAndAdvisorsForBean(Class beanClass, String beanName, TargetSource targetSource) {
        List advisors = this.findEligibleAdvisors(beanClass, beanName);
        return advisors.isEmpty()?DO_NOT_PROXY:advisors.toArray();
    }

    protected List<Advisor> findEligibleAdvisors(Class beanClass, String beanName) {
        List candidateAdvisors = this.findCandidateAdvisors();
        List eligibleAdvisors = this.findAdvisorsThatCanApply(candidateAdvisors, beanClass, beanName);
        this.extendAdvisors(eligibleAdvisors);
        if(!eligibleAdvisors.isEmpty()) {
            eligibleAdvisors = this.sortAdvisors(eligibleAdvisors);
        }

        return eligibleAdvisors;
    }

    protected List<Advisor> findCandidateAdvisors() {
        return this.advisorRetrievalHelper.findAdvisorBeans();
    }
最終調用findAdvisorBeans方法 具體實現:

public List<Advisor> findAdvisorBeans() {
        String[] advisorNames = null;
        synchronized(this) {
            advisorNames = this.cachedAdvisorBeanNames;
            if(advisorNames == null) {
                advisorNames = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(this.beanFactory, Advisor.class, true, false);
                this.cachedAdvisorBeanNames = advisorNames;
            }
        }

        if(advisorNames.length == 0) {
            return new LinkedList();
        } else {
            LinkedList advisors = new LinkedList();
            String[] arr$ = advisorNames;
            int len$ = advisorNames.length;

            for(int i$ = 0; i$ < len$; ++i$) {
                String name = arr$[i$];
                if(this.isEligibleBean(name)) {
                    if(this.beanFactory.isCurrentlyInCreation(name)) {
                        if(logger.isDebugEnabled()) {
                            logger.debug("Skipping currently created advisor \'" + name + "\'");
                        }
                    } else {
                        try {
                            advisors.add(this.beanFactory.getBean(name, Advisor.class));
                        } catch (BeanCreationException var10) {
                            Throwable rootCause = var10.getMostSpecificCause();
                            if(rootCause instanceof BeanCurrentlyInCreationException) {
                                BeanCreationException bce = (BeanCreationException)rootCause;
                                if(this.beanFactory.isCurrentlyInCreation(bce.getBeanName())) {
                                    if(logger.isDebugEnabled()) {
                                        logger.debug("Skipping advisor \'" + name + "\' with dependency on currently created bean: " + var10.getMessage());
                                    }
                                    continue;
                                }
                            }

                            throw var10;
                        }
                    }
                }
            }

            return advisors;
        }
    }
advisorNames = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(this.beanFactory, Advisor.class, true, false);查找容器中 Advisor類型的類


回頭看postProcessBeforeInstantiation方法  在獲取到advice和advisor以後,就對滿足條件的類生產代理對象

Object proxy = this.createProxy(beanClass, beanName, specificInterceptors, targetSource);


createProxy方法這裏暫且不作深入分析,我們從方法名知道是創建代理對象


補充:那爲什麼getBean時候 回去調用AbstractAutoProxyCreator 的 postProcessAfterInitialization方法呢

          

          結合前面對bean加載過程的分析,我們可以看到 在spring容器啓動的時候,refresh()方法中

             // Register bean processors that intercept bean creation.
                registerBeanPostProcessors(beanFactory);

           向bean工廠註冊 beanPostProcessors 具體實現:

       

public static void registerBeanPostProcessors(
			ConfigurableListableBeanFactory beanFactory, AbstractApplicationContext applicationContext) {
                  // 獲取類型爲BeanPostProcessor的所有beanName
		String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanPostProcessor.class, true, false);

		// Register BeanPostProcessorChecker that logs an info message when
		// a bean is created during BeanPostProcessor instantiation, i.e. when
		// a bean is not eligible for getting processed by all BeanPostProcessors.
		int beanProcessorTargetCount = beanFactory.getBeanPostProcessorCount() + 1 + postProcessorNames.length;
		beanFactory.addBeanPostProcessor(new BeanPostProcessorChecker(beanFactory, beanProcessorTargetCount));

		// Separate between BeanPostProcessors that implement PriorityOrdered,
		// Ordered, and the rest.
		List<BeanPostProcessor> priorityOrderedPostProcessors = new ArrayList<BeanPostProcessor>();
		List<BeanPostProcessor> internalPostProcessors = new ArrayList<BeanPostProcessor>();
		List<String> orderedPostProcessorNames = new ArrayList<String>();
		List<String> nonOrderedPostProcessorNames = new ArrayList<String>();
		for (String ppName : postProcessorNames) {
			if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
                                      //循環獲取對應的bean 加入到 列表中
                                 BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
				priorityOrderedPostProcessors.add(pp);
				if (pp instanceof MergedBeanDefinitionPostProcessor) {
					internalPostProcessors.add(pp);
				}
			}
			else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
				orderedPostProcessorNames.add(ppName);
			}
			else {
				nonOrderedPostProcessorNames.add(ppName);
			}
		}

		// First, register the BeanPostProcessors that implement PriorityOrdered.
		sortPostProcessors(beanFactory, priorityOrderedPostProcessors);
		registerBeanPostProcessors(beanFactory, priorityOrderedPostProcessors);

		// Next, register the BeanPostProcessors that implement Ordered.
		List<BeanPostProcessor> orderedPostProcessors = new ArrayList<BeanPostProcessor>();
		for (String ppName : orderedPostProcessorNames) {
			BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
			orderedPostProcessors.add(pp);
			if (pp instanceof MergedBeanDefinitionPostProcessor) {
				internalPostProcessors.add(pp);
			}
		}
		sortPostProcessors(beanFactory, orderedPostProcessors);
		registerBeanPostProcessors(beanFactory, orderedPostProcessors);

		// Now, register all regular BeanPostProcessors.
		List<BeanPostProcessor> nonOrderedPostProcessors = new ArrayList<BeanPostProcessor>();
		for (String ppName : nonOrderedPostProcessorNames) {
			BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
			nonOrderedPostProcessors.add(pp);
			if (pp instanceof MergedBeanDefinitionPostProcessor) {
				internalPostProcessors.add(pp);
			}
		}
		registerBeanPostProcessors(beanFactory, nonOrderedPostProcessors);

		// Finally, re-register all internal BeanPostProcessors.
		sortPostProcessors(beanFactory, internalPostProcessors);
		registerBeanPostProcessors(beanFactory, internalPostProcessors);

		beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(applicationContext));
	}
registerBeanPostProcessors 方法如下:      
private static void registerBeanPostProcessors(
			ConfigurableListableBeanFactory beanFactory, List<BeanPostProcessor> postProcessors) {

		for (BeanPostProcessor postProcessor : postProcessors) {
			beanFactory.addBeanPostProcessor(postProcessor);
		}
	}

addBeanPostProcessor:

public void addBeanPostProcessor(BeanPostProcessor beanPostProcessor) {
		Assert.notNull(beanPostProcessor, "BeanPostProcessor must not be null");
		this.beanPostProcessors.remove(beanPostProcessor);
		this.beanPostProcessors.add(beanPostProcessor);
		if (beanPostProcessor instanceof InstantiationAwareBeanPostProcessor) {
			this.hasInstantiationAwareBeanPostProcessors = true;
		}
		if (beanPostProcessor instanceof DestructionAwareBeanPostProcessor) {
			this.hasDestructionAwareBeanPostProcessors = true;
		}
	}

可以看到是對 最終存儲在 beanFactory 的 beanPostProcessors中  而我們的AbstractAutoProxyCreator 實現了 BeanPostProcessor 所以也會保存在列表中


回頭再來看  getBean的過程  前面文章已經分析過  就不再囉嗦 直接跳到重點地方  doCreateBean方法中

try {
			populateBean(beanName, mbd, instanceWrapper);
			if (exposedObject != null) {
				exposedObject = initializeBean(beanName, exposedObject, mbd);
			}
		}

初始化bean 方法具體實現:

wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);

看看方法具體實現:

@Override
	public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName)
			throws BeansException {

		Object result = existingBean;
		for (BeanPostProcessor beanProcessor : getBeanPostProcessors()) {
			result = beanProcessor.postProcessAfterInitialization(result, beanName);
			if (result == null) {
				return result;
			}
		}
		return result;
	}

循環調用 beanPostProcessor的 postProcessAfterInitialization方法 而 getBeanPostProcessors實際就是容器啓動時候 我們向beanFactory註冊的 beanPostProcessors屬性


到此就徹底清楚了爲什麼每次獲取bean的時候  都會經過AbstractAutoProxyCreator來生成代理對象

     



    

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章