spring-aop
2019-01-19 本文已影响0人
modou1618
一 类结构
类结构图.png- AbstractAutoProxyCreator模版方法查找aop配置bean,并创建代理,实现BeanPostProcessor接口,插入到spring 容器bean初始化流程中
- AbstractAdvisorAutoProxyCreator缓存aop相关配置bean,并提供查找和目标bean代理匹配处理
- AspectJAwareAdvisorAutoProxyCreator支持aop代理排序
- AnnotationAwareAspectJAutoProxyCreator支持注解代理处理
二 aop创建流程
aop创建.png2.1 注解的aop创建
- AnnotationAwareAspectJAutoProxyCreator通过实现接口
findCandidateAdvisors
对aspectj的注解进行处理
protected List<Advisor> findCandidateAdvisors() {
//获取xml标签定义的aop相关配置bean
List<Advisor> advisors = super.findCandidateAdvisors();
//获取注解标记的aop相关配置bean
advisors.addAll(this.aspectJAdvisorsBuilder.buildAspectJAdvisors());
return advisors;
}
- 获取包含Aspect注解或者是ajc编译器编译的类
public List<Advisor> buildAspectJAdvisors() {
List<String> aspectNames = null;
synchronized (this) {
aspectNames = this.aspectBeanNames;
if (aspectNames == null) {
List<Advisor> advisors = new LinkedList<Advisor>();
aspectNames = new LinkedList<String>();
String[] beanNames =
BeanFactoryUtils.beanNamesForTypeIncludingAncestors(this.beanFactory, Object.class, true, false);//获取所有bean
for (String beanName : beanNames) {
if (!isEligibleBean(beanName)) {
continue;
}
// 获取bean类型
Class<?> beanType = this.beanFactory.getType(beanName);
if (beanType == null) {
continue;
}
//包含Aspect注解或者是ajc编译器编译的类
if (this.advisorFactory.isAspect(beanType)) {
aspectNames.add(beanName);
AspectMetadata amd = new AspectMetadata(beanType, beanName);
if (amd.getAjType().getPerClause().getKind() == PerClauseKind.SINGLETON) {
MetadataAwareAspectInstanceFactory factory =
new BeanFactoryAspectInstanceFactory(this.beanFactory, beanName);
List<Advisor> classAdvisors = this.advisorFactory.getAdvisors(factory);
if (this.beanFactory.isSingleton(beanName)) {
this.advisorsCache.put(beanName, classAdvisors);
}
else {
this.aspectFactoryCache.put(beanName, factory);
}
advisors.addAll(classAdvisors);
}
else {
// Per target or per this.
if (this.beanFactory.isSingleton(beanName)) {
throw new IllegalArgumentException("Bean with name '" + beanName +
"' is a singleton, but aspect instantiation model is not singleton");
}
MetadataAwareAspectInstanceFactory factory =
new PrototypeAspectInstanceFactory(this.beanFactory, beanName);
this.aspectFactoryCache.put(beanName, factory);
advisors.addAll(this.advisorFactory.getAdvisors(factory));
}
}
}
this.aspectBeanNames = aspectNames;
return advisors;
}
}
if (aspectNames.isEmpty()) {
return Collections.emptyList();
}
List<Advisor> advisors = new LinkedList<Advisor>();
for (String aspectName : aspectNames) {
List<Advisor> cachedAdvisors = this.advisorsCache.get(aspectName);
if (cachedAdvisors != null) {
advisors.addAll(cachedAdvisors);
}
else {
MetadataAwareAspectInstanceFactory factory = this.aspectFactoryCache.get(aspectName);
advisors.addAll(this.advisorFactory.getAdvisors(factory));
}
}
return advisors;
}