2、AnnotationAwareAspectJAutoProxyCreator的解析

@Override 

public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {

if (bean != null) {

Object cacheKey = getCacheKey(bean.getClass(), beanName);

if (!this.earlyProxyReferences.contains(cacheKey)) {

return wrapIfNecessary(bean, beanName, cacheKey);

}

}

return bean;

}



protected Object wrapIfNecessary(Object bean, String beanName, Object cacheKey) {

//已经创建

if (beanName != null && this.targetSourcedBeans.contains(beanName)) {

return bean;

}

if (Boolean.FALSE.equals(this.advisedBeans.get(cacheKey))) {

return bean;

}

//基础类或者应该忽略的类,不被通知

if (isInfrastructureClass(bean.getClass()) || shouldSkip(bean.getClass(), beanName)) {

this.advisedBeans.put(cacheKey, Boolean.FALSE);

return bean;

}

// 寻找需要增强器 切面

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;

}

this.advisedBeans.put(cacheKey, Boolean.FALSE);

return bean;

}


AnnotationAwareAspectJAutoProxyCreator 实现了BeanPostProcessor,为需要增强的bean创建代理。重点是寻找需要增强器



@Overrideprotected Object[] getAdvicesAndAdvisorsForBean(ClassbeanClass, String beanName, TargetSource targetSource) { Listadvisors = findEligibleAdvisors(beanClass, beanName);

if (advisors.isEmpty()) {

return DO_NOT_PROXY;

}

return advisors.toArray();

}


若不存在切面,则不需要创建代理


protected ListfindEligibleAdvisors(ClassbeanClass, String beanName) {  

ListcandidateAdvisors = findCandidateAdvisors();

ListeligibleAdvisors = findAdvisorsThatCanApply(candidateAdvisors, beanClass, beanName);

extendAdvisors(eligibleAdvisors);

if (!eligibleAdvisors.isEmpty()) {

eligibleAdvisors = sortAdvisors(eligibleAdvisors);

}

return eligibleAdvisors;

}


@Override protected List findCandidateAdvisors() {

List advisors = super.findCandidateAdvisors();

advisors.addAll(this.aspectJAdvisorsBuilder.buildAspectJAdvisors());

return advisors;

}

下面分析findCandidateAdvisors方法寻找所有的切面,super.findCandidateAdvisors()寻找 例如xml或其他定义的切面 ,下面aspectJAdvisorsBuilder.buildAspectJAdvisors()寻找@aspect定义得切面。

接下来再对该实现进行探讨

你可能感兴趣的:(2、AnnotationAwareAspectJAutoProxyCreator的解析)