SPRING源码学习之路(三)——<aop:config>自动代理的实现

来源:互联网 发布:贵州大数据发展报告 编辑:程序博客网 时间:2024/05/29 17:29


        关于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的所有beanNameString[] 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);

看看方法具体实现:

@Overridepublic 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来生成代理对象

     



    

0 0
原创粉丝点击