栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

AOP学习总结

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

AOP学习总结

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档

文章目录
  • 前言
  • 一、一个小Demo
  • 二、自定义标签
  • 三、BeanPostProcessor
  • 四、AOP的入口
    • 4.1、拿到针对该bean的所有增强方法
      • 4.1.1、获取所有候选的增强方法
        • 4.1.1.1、获取所有实现Advisor.class的对象
        • 4.1.1.2、获取所有注释了@Aspect 注解的类对象
      • 4.1.2、从候选增强中找到目标bean需要的增强方法
    • 4.2、生成代理对象
      • 4.2.1、获取生成代理对象的工厂
      • 4.2.2、获取生成代理对象
      • 4.2.2.1、生成增强方法执行链
      • 4.2.2.2、调用增强方法执行链
  • 总结


前言

刚刚对IOC的学习做了一个总结,现在要开始对AOP的学习做总结了。学习什么都需要找一个入口,之前总结IOC时入口就是创建容器对象的构造方法。相比较而言AOP的入口比较难找。需要做一些铺垫,并且还要结合IOC的主流程。


一、一个小Demo

还是先看源码的一个小demo

在容器中获取一个对象,发现取出来的对象是个代理对象。太诡异了,在看看配置文件




	
		
		
		

		
			
			
			
			
		

	

	

	

	

	


发现除了bean标签以外还多了一堆aop开头的自定义标签。要想找到aop的入口就需要从自定义标签入手


二、自定义标签

在Bean定义解析注册流程总结的结尾有一个分支。解析默认标签和解析自定义标签。总结中走的是默认标签分支。这里需要看以下自定义标签分支

public class DefaultBeanDefinitionDocumentReader implements BeanDefinitionDocumentReader {
	//解析bean定义信息
	protected void parseBeanDefinitions(Element root, BeanDefinitionParserDelegate delegate) {
		if (delegate.isDefaultNamespace(root)) {
			NodeList nl = root.getChildNodes();
			for (int i = 0; i < nl.getLength(); i++) {
				Node node = nl.item(i);
				if (node instanceof Element) {
					Element ele = (Element) node;
					if (delegate.isDefaultNamespace(ele)) {
					    //之前走的这个分支
						parseDefaultElement(ele, delegate);
					}
					else {
					    //这次要走这个分支
						delegate.parseCustomElement(ele);
					}
				}
			}
		}
		else {
			delegate.parseCustomElement(root);
		}
	}
}

关于自定义标签的详细总结不在这里展开了,详细内容在自定义标签总结
知道自定义标签AOP标签向容器中注册了一个类AspectJAwareAdvisorAutoProxyCreator就可以了

在这张图中可以发现AspectJAwareAdvisorAutoProxyCreator本质上是一个BeanPostProcessor。那么BeanPostProcessor又是什么呢?


三、BeanPostProcessor

回到容器初始化流程中,可以看到流程中有一个registerBeanPostProcessors方法

public void refresh() throws BeansException, IllegalStateException {
		synchronized (this.startupShutdownMonitor) {
			。。。省略代码
			try {
				。。。省略代码
				
				// 会在bean实例化后 初始化的前后分别调用每个册BeanPostProcessor的这两个实现方法 AOP就是一个BeanPostProcessor
				registerBeanPostProcessors(beanFactory);

				。。。省略代码
	}

所有实现了BeanPostProcessor接口的类,都会实现两个接口

容器会将这些对象封装到一个集合中。当一个bean实例实例化后初始化前会循环一遍BeanPostProcessor对象集合,把bean作为参数传进去挨个执行一次postProcessBeforeInitialization方法。在bean初始化后会在循环一遍BeanPostProcessor对象集合,把bean作为参数传进去挨个在执行一次。

public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory
		implements AutowireCapableBeanFactory {
	//初始化bean
	protected Object initializeBean(final String beanName, final Object bean, @Nullable RootBeanDefinition mbd) {
		if (System.getSecurityManager() != null) {
			AccessController.doPrivileged((PrivilegedAction) () -> {
				invokeAwareMethods(beanName, bean);
				return null;
			}, getAccessControlContext());
		}
		else {
			invokeAwareMethods(beanName, bean);
		}

		Object wrappedBean = bean;
		if (mbd == null || !mbd.isSynthetic()) {
			//前置处理
			wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
		}

		try {
			invokeInitMethods(beanName, wrappedBean, mbd);
		}
		catch (Throwable ex) {
			throw new BeanCreationException(
					(mbd != null ? mbd.getResourceDescription() : null),
					beanName, "Invocation of init method failed", ex);
		}
		if (mbd == null || !mbd.isSynthetic()) {
			//后置处理
			wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
		}

		return wrappedBean;
	}
	
	//前置处理	
	@Override
	public Object applyBeanPostProcessorsBeforeInitialization(Object existingBean, String beanName)
			throws BeansException {

		Object result = existingBean;
		//便利执行所有的后置处理器的postProcessBeforeInitialization方法
		for (BeanPostProcessor processor : getBeanPostProcessors()) {
			Object current = processor.postProcessBeforeInitialization(result, beanName);
			if (current == null) {
				return result;
			}
			result = current;
		}
		return result;
	}
	
	//后置处理
	@Override
	public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName)
			throws BeansException {

		Object result = existingBean;
		//便利执行所有的后置处理器的postProcessAfterInitialization方法
		for (BeanPostProcessor processor : getBeanPostProcessors()) {
			Object current = processor.postProcessAfterInitialization(result, beanName);
			if (current == null) {
				return result;
			}
			result = current;
		}
		return result;
	}
}
 

对象只有初始化后才能被代理,所有重点应该就在AspectJAwareAdvisorAutoProxyCreator类的postProcessAfterInitialization方法中。
最终发现AspectJAwareAdvisorAutoProxyCreator类的爷爷AbstractAutoProxyCreator对postProcessAfterInitialization方法做了实现。这样AOP的入口就找到了。就是AbstractAutoProxyCreator.postProcessAfterInitialization方法

四、AOP的入口

首先看看AbstractAutoProxyCreator的postProcessAfterInitialization方法

public abstract class AbstractAutoProxyCreator extends ProxyProcessorSupport
		implements SmartInstantiationAwareBeanPostProcessor, BeanFactoryAware {
		//AOP入口方法
		public Object postProcessAfterInitialization(@Nullable Object bean, String beanName) {
		//这里的bean就是容器初始化好了的bean 首先判断下bean是否需要被代理 于是进入到了wrapIfNecessary方法里
				if (bean != null) {
					Object cacheKey = getCacheKey(bean.getClass(), beanName);
					if (this.earlyProxyReferences.remove(cacheKey) != bean) {
						return wrapIfNecessary(bean, beanName, cacheKey);
					}
				}
				return bean;
	   }	
	   
		//AOP入口方法
		protected Object wrapIfNecessary(Object bean, String beanName, Object cacheKey) {
			。。。省略代码
			//拿到针对该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;
		}
}

这里需要跟两个方法
1 getAdvicesAndAdvisorsForBean 拿到针对该bean的所有增强方法
2 createProxy 生成代理对象

4.1、拿到针对该bean的所有增强方法

这部分的整体流程统一由AbstractAdvisorAutoProxyCreator来制定的
跟 getAdvicesAndAdvisorsForBean

public abstract class AbstractAdvisorAutoProxyCreator extends AbstractAutoProxyCreator {
	//获取所有符合要求的增强类
	protected Object[] getAdvicesAndAdvisorsForBean(
				Class beanClass, String beanName, @Nullable TargetSource targetSource) {
			//拿到所有符合要求的增强方法
			List advisors = findEligibleAdvisors(beanClass, beanName);
			//如果没有 返回不代理
			if (advisors.isEmpty()) {
				return DO_NOT_PROXY;
			}
			return advisors.toArray();
		}
	//获取所有符合要求的增强类
	protected List findEligibleAdvisors(Class beanClass, String beanName) {
			//这里拿到了容器中所有的增强方法
			List candidateAdvisors = findCandidateAdvisors();
			//过滤出目标类需要的增强方法
			List eligibleAdvisors = findAdvisorsThatCanApply(candidateAdvisors, beanClass, beanName);
			extendAdvisors(eligibleAdvisors);
			if (!eligibleAdvisors.isEmpty()) {
				eligibleAdvisors = sortAdvisors(eligibleAdvisors);
			}
			return eligibleAdvisors;
		}
}

这里又分了两个分支
findCandidateAdvisors和findAdvisorsThatCanApply

4.1.1、获取所有候选的增强方法

获取所有候选的advisor是由AnnotationAwareAspectJAutoProxyCreator类完成的
跟 findCandidateAdvisors

public class AnnotationAwareAspectJAutoProxyCreator extends AspectJAwareAdvisorAutoProxyCreator {
protected List findCandidateAdvisors() {
	// Add all the Spring advisors found according to superclass rules.
		//委托爷爷类 获取所有实现Advisor.class的对象
		List advisors = super.findCandidateAdvisors();
		// Build Advisors for all AspectJ aspects in the bean factory.
		//获取所有注释了@Aspect 注解的类对象
		//委托给了aspectJAdvisorsBuilder类
		if (this.aspectJAdvisorsBuilder != null) {
			advisors.addAll(this.aspectJAdvisorsBuilder.buildAspectJAdvisors());
		}
		return advisors;
	}
}

这里又有了两个分支

4.1.1.1、获取所有实现Advisor.class的对象

跟 爷爷类的findCandidateAdvisors

public abstract class AbstractAdvisorAutoProxyCreator extends AbstractAutoProxyCreator {
	protected List findCandidateAdvisors() {
			Assert.state(this.advisorRetrievalHelper != null, "No BeanFactoryAdvisorRetrievalHelper available");
			//委托给advisorRetrievalHelper来处理
			return this.advisorRetrievalHelper.findAdvisorBeans();
		}
}	

跟 findAdvisorBeans
BeanFactoryAdvisorRetrievalHelper 这个类主要就一个方法,就是将工厂中所有Advisor类型的bean,都放入容器中,并将Advisor集合返回

public class BeanFactoryAdvisorRetrievalHelper {
	public List findAdvisorBeans() {
			//获取容器中所有Advisor类型的类的名称
			String[] advisorNames = this.cachedAdvisorBeanNames;
			if (advisorNames == null) {
				// Do not initialize FactoryBeans here: We need to leave all regular beans
				// uninitialized to let the auto-proxy creator apply to them!
				advisorNames = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(
						this.beanFactory, Advisor.class, true, false);
				this.cachedAdvisorBeanNames = advisorNames;
			}
			。。。省略代码
			for (String name : advisorNames) {
				if (isEligibleBean(name)) {
					if (this.beanFactory.isCurrentlyInCreation(name)) {
						if (logger.isTraceEnabled()) {
							logger.trace("Skipping currently created advisor '" + name + "'");
						}
					}
					else {
						try {
							//一次创建并加入到advisors中 返回
							advisors.add(this.beanFactory.getBean(name, Advisor.class));
						}
						catch (BeanCreationException ex) {
							。。。省略代码
						}
					}
				}
			}
			return advisors;
		}
}
4.1.1.2、获取所有注释了@Aspect 注解的类对象

跟 buildAspectJAdvisors

//该类主要用于将注释了@AspectJ的bean转化为Advisor对象
public class BeanFactoryAspectJAdvisorsBuilder {
	public BeanFactoryAspectJAdvisorsBuilder(ListableBeanFactory beanFactory) {
		this(beanFactory, new ReflectiveAspectJAdvisorFactory(beanFactory));
	}
	public BeanFactoryAspectJAdvisorsBuilder(ListableBeanFactory beanFactory, AspectJAdvisorFactory advisorFactory) {
		Assert.notNull(beanFactory, "ListableBeanFactory must not be null");
		Assert.notNull(advisorFactory, "AspectJAdvisorFactory must not be null");
		this.beanFactory = beanFactory;
		//这里可以看到 this.advisorFactory本身是一个ReflectiveAspectJAdvisorFactory
		this.advisorFactory = advisorFactory;
	}

	//bean工厂
	private final ListableBeanFactory beanFactory;
	//用于保存所有注释了@AspectJ的bean名称
	private volatile List aspectBeanNames;
	//用于缓存Advisor对象 其中key是beanName value是bean对应的Advisor
	private final Map> advisorsCache = new ConcurrentHashMap<>();
	//用于缓存AbstractAspectJAdvisorFactory元数据工厂【MetadataAwareAspectInstanceFactory】
	//MetadataAwareAspectInstanceFactory的实现是BeanFactoryAspectInstanceFactory类
	//BeanFactoryAspectInstanceFactory的作用是封装了一个注释了@AspectJ类的元数据
	//元数据包括 bean名称 bean类型 和一个获取bean对象的方法
	private final Map aspectFactoryCache = new ConcurrentHashMap<>();
	//本身是一个ReflectiveAspectJAdvisorFactory类 用于构建Advisor对象的
	private final AspectJAdvisorFactory advisorFactory;
	
	//获取所有@AspectJ注释的bean
	//将bean的元数据信息封装成一个MetadataAwareAspectInstanceFactory
	//将每一个注释了@AspectJ的bean转化为一组Advisor对象【由AspectJAdvisorFactory来完成,AspectJAdvisorFactory中需要MetadataAwareAspectInstanceFactory】
	//最后将所有Advisor对象封装到集合中返回
	public List buildAspectJAdvisors() {
			List aspectNames = this.aspectBeanNames;
	
			if (aspectNames == null) {
				synchronized (this) {
					aspectNames = this.aspectBeanNames;
					if (aspectNames == null) {
						List advisors = new ArrayList<>();
						aspectNames = new ArrayList<>();
						//获取所有bean名称
						String[] beanNames = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(
								this.beanFactory, Object.class, true, false);
						for (String beanName : beanNames) {
							。。。省略代码
							//这里判断bean是否带有@Aspect注解
							if (this.advisorFactory.isAspect(beanType)) {
								aspectNames.add(beanName);
								AspectMetadata amd = new AspectMetadata(beanType, beanName);
								if (amd.getAjType().getPerClause().getKind() == PerClauseKind.SINGLETON) {
									//这是一个专门产生@Aspect注释对象的工厂
									//最终会委托this.beanFactory来创建Aspect对象
									MetadataAwareAspectInstanceFactory factory =
											new BeanFactoryAspectInstanceFactory(this.beanFactory, beanName);
									//需要跟这里		
									//这里的 this.advisorFactory==ReflectiveAspectJAdvisorFactory 
									List 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 {
									。。。省略代码
								}
							}
						}
						this.aspectBeanNames = aspectNames;
						return advisors;
					}
				}
			}
			//后续就都在缓存中取了
			if (aspectNames.isEmpty()) {
				return Collections.emptyList();
			}
			List advisors = new ArrayList<>();
			for (String aspectName : aspectNames) {
				List 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;
		}
}			

跟ReflectiveAspectJAdvisorFactory

public class ReflectiveAspectJAdvisorFactory extends AbstractAspectJAdvisorFactory implements Serializable {
		//将注释了@AspectJ注释的bean的元数据 转化为一组Advisor对象
		public List getAdvisors(MetadataAwareAspectInstanceFactory aspectInstanceFactory) {
			//获取元数据 类类型
			Class aspectClass = aspectInstanceFactory.getAspectMetadata().getAspectClass();
			//获取元数据bean 名称
			String aspectName = aspectInstanceFactory.getAspectMetadata().getAspectName();
			validate(aspectClass);
	
			// We need to wrap the MetadataAwareAspectInstanceFactory with a decorator
			// so that it will only instantiate once.
			//把aspectInstanceFactory封一层的目的是为了单例
			//获取实例后LazySingletonAspectInstanceFactoryDecorator对象会将实例缓存到成员变量中,这样每次获取元对象实例时只会调用一次bean工厂的getBean方法
			MetadataAwareAspectInstanceFactory lazySingletonAspectInstanceFactory =
					new LazySingletonAspectInstanceFactoryDecorator(aspectInstanceFactory);
	
			List advisors = new ArrayList<>();
			//拿到切面对象中所有非切入点注释的方法
			//拿到了一堆 Around.class, Before.class, After.class, AfterReturning.class, AfterThrowing.class
			for (Method method : getAdvisorMethods(aspectClass)) {
				//跟这里
				//将注释了@AspectJ注释的bean的每一个注释了advice注解的方法 转化为Advisor对象
				Advisor advisor = getAdvisor(method, lazySingletonAspectInstanceFactory, advisors.size(), aspectName);
				if (advisor != null) {
					advisors.add(advisor);
				}
			}
	
			// If it's a per target aspect, emit the dummy instantiating aspect.
			if (!advisors.isEmpty() && lazySingletonAspectInstanceFactory.getAspectMetadata().isLazilyInstantiated()) {
				Advisor instantiationAdvisor = new SyntheticInstantiationAdvisor(lazySingletonAspectInstanceFactory);
				advisors.add(0, instantiationAdvisor);
			}
	
			// Find introduction fields.
			for (Field field : aspectClass.getDeclaredFields()) {
				Advisor advisor = getDeclareParentsAdvisor(field);
				if (advisor != null) {
					advisors.add(advisor);
				}
			}
	
			return advisors;
	}
	
	//将bean的每一个注释了advice注解的方法 转化为Advisor对象
	public Advisor getAdvisor(Method candidateAdviceMethod, MetadataAwareAspectInstanceFactory aspectInstanceFactory,
			int declarationOrderInAspect, String aspectName) {

		validate(aspectInstanceFactory.getAspectMetadata().getAspectClass());
		//拿到advice的切入点表达式
		AspectJExpressionPointcut expressionPointcut = getPointcut(
				candidateAdviceMethod, aspectInstanceFactory.getAspectMetadata().getAspectClass());
		if (expressionPointcut == null) {
			return null;
		}
		//构成最终的advisor对象
		return new InstantiationModelAwarePointcutAdvisorImpl(expressionPointcut, candidateAdviceMethod,
				this, aspectInstanceFactory, declarationOrderInAspect, aspectName);
	}

	
}	

跟 InstantiationModelAwarePointcutAdvisorImpl 构造器

public InstantiationModelAwarePointcutAdvisorImpl(AspectJExpressionPointcut declaredPointcut,
			Method aspectJAdviceMethod, AspectJAdvisorFactory aspectJAdvisorFactory,
			MetadataAwareAspectInstanceFactory aspectInstanceFactory, int declarationOrder, String aspectName) {
		//封装了切入点表达式的对象
		this.declaredPointcut = declaredPointcut;
		//advice方法类类型
		this.declaringClass = aspectJAdviceMethod.getDeclaringClass();
		//advice方法名称
		this.methodName = aspectJAdviceMethod.getName();
		//advice方法参数类型
		this.parameterTypes = aspectJAdviceMethod.getParameterTypes();
		//advice方法
		this.aspectJAdviceMethod = aspectJAdviceMethod;
		this.aspectJAdvisorFactory = aspectJAdvisorFactory;
		//缓存了aspect对象的工厂
		this.aspectInstanceFactory = aspectInstanceFactory;
		//方法在类中的顺序
		this.declarationOrder = declarationOrder;
		//切面名称
		this.aspectName = aspectName;

		if (aspectInstanceFactory.getAspectMetadata().isLazilyInstantiated()) {
			// Static part of the pointcut is a lazy type.
			Pointcut preInstantiationPointcut = Pointcuts.union(
					aspectInstanceFactory.getAspectMetadata().getPerClausePointcut(), this.declaredPointcut);

			// Make it dynamic: must mutate from pre-instantiation to post-instantiation state.
			// If it's not a dynamic pointcut, it may be optimized out
			// by the Spring AOP infrastructure after the first evaluation.
			this.pointcut = new PerTargetInstantiationModelPointcut(
					this.declaredPointcut, preInstantiationPointcut, aspectInstanceFactory);
			this.lazy = true;
		}
		else {
			// A singleton aspect.
			this.pointcut = this.declaredPointcut;
			this.lazy = false;
			//最终在这里封装出了advice对象
			this.instantiatedAdvice = instantiateAdvice(this.declaredPointcut);
		}

		//构建advice对象
		private Advice instantiateAdvice(AspectJExpressionPointcut pointcut) {
	        //跟getAdvice
			Advice advice = this.aspectJAdvisorFactory.getAdvice(this.aspectJAdviceMethod, pointcut,
					this.aspectInstanceFactory, this.declarationOrder, this.aspectName);
			return (advice != null ? advice : EMPTY_ADVICE);
		}
	}

跟 getAdvice
又回到了ReflectiveAspectJAdvisorFactory类中,
之前构建Advisor类就是在这个类完成的

public class ReflectiveAspectJAdvisorFactory extends AbstractAspectJAdvisorFactory implements Serializable {
public Advice getAdvice(Method candidateAdviceMethod, AspectJExpressionPointcut expressionPointcut,
			MetadataAwareAspectInstanceFactory aspectInstanceFactory, int declarationOrder, String aspectName) {

		Class candidateAspectClass = aspectInstanceFactory.getAspectMetadata().getAspectClass();
		validate(candidateAspectClass);

		AspectJAnnotation aspectJAnnotation =
				AbstractAspectJAdvisorFactory.findAspectJAnnotationOnMethod(candidateAdviceMethod);
		。。。省略代码

		AbstractAspectJAdvice springAdvice;

		switch (aspectJAnnotation.getAnnotationType()) {
		    //切入点不是方法 所以不生成advice
			case AtPointcut:
				if (logger.isDebugEnabled()) {
					logger.debug("Processing pointcut '" + candidateAdviceMethod.getName() + "'");
				}
				return null;
			case AtAround:
				springAdvice = new AspectJAroundAdvice(
						candidateAdviceMethod, expressionPointcut, aspectInstanceFactory);
				break;
			case AtBefore:
				springAdvice = new AspectJMethodBeforeAdvice(
						candidateAdviceMethod, expressionPointcut, aspectInstanceFactory);
				break;
			case AtAfter:
				springAdvice = new AspectJAfterAdvice(
						candidateAdviceMethod, expressionPointcut, aspectInstanceFactory);
				break;
			case AtAfterReturning:
				springAdvice = new AspectJAfterReturningAdvice(
						candidateAdviceMethod, expressionPointcut, aspectInstanceFactory);
				AfterReturning afterReturningAnnotation = (AfterReturning) aspectJAnnotation.getAnnotation();
				if (StringUtils.hasText(afterReturningAnnotation.returning())) {
					springAdvice.setReturningName(afterReturningAnnotation.returning());
				}
				break;
			case AtAfterThrowing:
				springAdvice = new AspectJAfterThrowingAdvice(
						candidateAdviceMethod, expressionPointcut, aspectInstanceFactory);
				AfterThrowing afterThrowingAnnotation = (AfterThrowing) aspectJAnnotation.getAnnotation();
				if (StringUtils.hasText(afterThrowingAnnotation.throwing())) {
					springAdvice.setThrowingName(afterThrowingAnnotation.throwing());
				}
				break;
			default:
				throw new UnsupportedOperationException(
						"Unsupported advice type on method: " + candidateAdviceMethod);
		}

		// Now to configure the advice...
		springAdvice.setAspectName(aspectName);
		springAdvice.setDeclarationOrder(declarationOrder);
		String[] argNames = this.parameterNameDiscoverer.getParameterNames(candidateAdviceMethod);
		if (argNames != null) {
			springAdvice.setArgumentNamesFromStringArray(argNames);
		}
		springAdvice.calculateArgumentBindings();

		return springAdvice;
	}
}	

为什么每个advice对象 构造器都有candidateAdviceMethod, expressionPointcut, aspectInstanceFactory这三个参数
想一想反射的方法调用candidateAdviceMethod.invoke(aspectInstanceFactory.getAspectInstance(),参数); aspectInstanceFactory还记得这里缓存了一个切面对象吗。这样的话Advice对象其实就具备了执行增强方法的所有条件了。
expressionPointcut 这个应该就是用作后续的增强判断了 判断被代理的方法和增强方法是否匹配

4.1.2、从候选增强中找到目标bean需要的增强方法

继续跟另一个分支 findAdvisorsThatCanApply,又回到了AbstractAdvisorAutoProxyCreator类中

public abstract class AbstractAdvisorAutoProxyCreator extends AbstractAutoProxyCreator {
	protected List findAdvisorsThatCanApply(
				List candidateAdvisors, Class beanClass, String beanName) {
	
			ProxyCreationContext.setCurrentProxiedBeanName(beanName);
			try {
				//主要委托给类AopUtils
				return AopUtils.findAdvisorsThatCanApply(candidateAdvisors, beanClass);
			}
			finally {
				ProxyCreationContext.setCurrentProxiedBeanName(null);
			}
		}
}		

AopUtils 类主要封装了一些对代理类的判断
跟findAdvisorsThatCanApply

public abstract class AopUtils {
	//从所有候选Advisor集合中找到和目标类匹配的Advisor集合
	public static List findAdvisorsThatCanApply(List candidateAdvisors, Class clazz) {
			if (candidateAdvisors.isEmpty()) {
				return candidateAdvisors;
			}
			List eligibleAdvisors = new ArrayList<>();
			//引介增强 这里先不看了
			for (Advisor candidate : candidateAdvisors) {
				if (candidate instanceof IntroductionAdvisor && canApply(candidate, clazz)) {
					eligibleAdvisors.add(candidate);
				}
			}
			boolean hasIntroductions = !eligibleAdvisors.isEmpty();
			//便利所有Advisor
			for (Advisor candidate : candidateAdvisors) {
				if (candidate instanceof IntroductionAdvisor) {
					// already processed
					continue;
				}
				//重点看canApply方法
				if (canApply(candidate, clazz, hasIntroductions)) {
					eligibleAdvisors.add(candidate);
				}
			}
			return eligibleAdvisors;
		}
		
		//用于判断当前Advisor和目标类是否匹配
		public static boolean canApply(Advisor advisor, Class targetClass, boolean hasIntroductions) {
			//引介的先不看了
			if (advisor instanceof IntroductionAdvisor) {
				return ((IntroductionAdvisor) advisor).getClassFilter().matches(targetClass);
			}
			else if (advisor instanceof PointcutAdvisor) {
			    //这里继续跟canApply,这是一个重载方法
				PointcutAdvisor pca = (PointcutAdvisor) advisor;
				//pca.getPointcut() 这里获取的就是AspectJExpressionPointcut对象
				//根据切入点判断advisor和目标对象是否匹配
				//继续跟这里
				return canApply(pca.getPointcut(), targetClass, hasIntroductions);
			}
			else {
				// It doesn't have a pointcut so we assume it applies.
				return true;
			}
	 }

		//根据切入点判断advisor和目标对象是否匹配
		public static boolean canApply(Pointcut pc, Class targetClass, boolean hasIntroductions) {
			Assert.notNull(pc, "Pointcut must not be null");
			//类级别匹配
			if (!pc.getClassFilter().matches(targetClass)) {
				return false;
			}
			//获取方法匹配器
			MethodMatcher methodMatcher = pc.getMethodMatcher();
			if (methodMatcher == MethodMatcher.TRUE) {
				// No need to iterate the methods if we're matching any method anyway...
				return true;
			}
			
			IntroductionAwareMethodMatcher introductionAwareMethodMatcher = null;
			if (methodMatcher instanceof IntroductionAwareMethodMatcher) {
				introductionAwareMethodMatcher = (IntroductionAwareMethodMatcher) methodMatcher;
			}
			//集合中保存目标对象和目标对象的所有父类
			Set> classes = new LinkedHashSet<>();
			if (!Proxy.isProxyClass(targetClass)) {
				classes.add(ClassUtils.getUserClass(targetClass));
			}
			//获取被代理类的所有父类
			classes.addAll(ClassUtils.getAllInterfacesForClassAsSet(targetClass));
	
			for (Class clazz : classes) {
				//获得类的所有方法
				Method[] methods = ReflectionUtils.getAllDeclaredMethods(clazz);
				for (Method method : methods) {
				    //执行匹配
					if (introductionAwareMethodMatcher != null ?
							introductionAwareMethodMatcher.matches(method, targetClass, hasIntroductions) :
							methodMatcher.matches(method, targetClass)) {
						return true;
					}
				}
			}
	
			return false;
		}
}

到这里目标bean需要的增强方法已经都找到了,剩下的就是创建代理对象了

4.2、生成代理对象

回到主流程wrapIfNecessary方法

public abstract class AbstractAutoProxyCreator extends ProxyProcessorSupport
		implements SmartInstantiationAwareBeanPostProcessor, BeanFactoryAware {
	//动态代理入口方法	
	protected Object wrapIfNecessary(Object bean, String beanName, Object cacheKey) {
			if (StringUtils.hasLength(beanName) && 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;
			}
	
			// Create proxy if we have advice.
			//这里刚刚已经跟完了 返回一堆Advisor
			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;
		}
		//获取代理对象
		protected Object createProxy(Class beanClass, @Nullable String beanName,
				@Nullable Object[] specificInterceptors, TargetSource targetSource) {
	
			if (this.beanFactory instanceof ConfigurableListableBeanFactory) {
				AutoProxyUtils.exposeTargetClass((ConfigurableListableBeanFactory) this.beanFactory, beanName, beanClass);
			}
	
			ProxyFactory proxyFactory = new ProxyFactory();
			proxyFactory.copyFrom(this);
	
			if (!proxyFactory.isProxyTargetClass()) {
				if (shouldProxyTargetClass(beanClass, beanName)) {
					proxyFactory.setProxyTargetClass(true);
				}
				else {
					evaluateProxyInterfaces(beanClass, proxyFactory);
				}
			}
			//格式统一成 advisor
			Advisor[] advisors = buildAdvisors(beanName, specificInterceptors);
			//这里将bean对应的所有advisors封装到proxyFactory里 后续需要委托proxyFactory来完成代理对象创建
			proxyFactory.addAdvisors(advisors);
			proxyFactory.setTargetSource(targetSource);
			customizeProxyFactory(proxyFactory);
	
			proxyFactory.setFrozen(this.freezeProxy);
			if (advisorsPreFiltered()) {
				proxyFactory.setPreFiltered(true);
			}
			//委托给ProxyFactory完成代理对象的创建
			return proxyFactory.getProxy(getProxyClassLoader());
		}
}		

ProxyFactory这个类主要就是用来创建代理对象的
跟 getProxy

public class ProxyFactory extends ProxyCreatorSupport {
	public Object getProxy(@Nullable ClassLoader classLoader) {
			return createAopProxy().getProxy(classLoader);
		}
}

这里有两个分支
1 createAopProxy() 生成代理对象工厂
2 getProxy() 生成代理对象

4.2.1、获取生成代理对象的工厂

跟 createAopProxy 进入了ProxyFactory 类的父类ProxyCreatorSupport 中

public class ProxyCreatorSupport extends AdvisedSupport {
	protected final synchronized AopProxy createAopProxy() {
			if (!this.active) {
				activate();
			}
			//getAopProxyFactory() = this.aopProxyFactory
			//this.aopProxyFactory默认实现类是DefaultAopProxyFactory,用于创建jdk代理或者CGlib代理的
			return getAopProxyFactory().createAopProxy(this);
		}
	
	public AopProxyFactory getAopProxyFactory() {
		return this.aopProxyFactory;
	}
}	

看下DefaultAopProxyFactory的createAopProxy方法

public class DefaultAopProxyFactory implements AopProxyFactory, Serializable {
	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() || Proxy.isProxyClass(targetClass)) {
					return new JdkDynamicAopProxy(config);
				}
				return new ObjenesisCglibAopProxy(config);
			}
			else {
				return new JdkDynamicAopProxy(config);
			}
		}
}

这里最终返回的是 使用Cglib还是JDK做代理

4.2.2、获取生成代理对象

回到刚刚的流程,createAopProxy我们假设返回的是jdk代理工厂【JdkDynamicAopProxy】
继续跟getProxy

public Object getProxy(@Nullable ClassLoader classLoader) {
      //假设createAopProxy()返回的就是JdkDynamicAopProxy
		return createAopProxy().getProxy(classLoader);
	}

进入JdkDynamicAopProxy 类 跟 getProxy

final class JdkDynamicAopProxy implements AopProxy, InvocationHandler, Serializable {
	//这里封装了所有的advisor
	private final AdvisedSupport advised;
	//构造器
	public JdkDynamicAopProxy(AdvisedSupport config) throws AopConfigException {
		Assert.notNull(config, "AdvisedSupport must not be null");
		if (config.getAdvisors().length == 0 && config.getTargetSource() == AdvisedSupport.EMPTY_TARGET_SOURCE) {
			throw new AopConfigException("No advisors and no TargetSource specified");
		}
		//初始化this.advised
		this.advised = config;
	}
	
	public Object getProxy(@Nullable ClassLoader classLoader) {
			if (logger.isTraceEnabled()) {
				logger.trace("Creating JDK dynamic proxy: " + this.advised.getTargetSource());
			}
			Class[] proxiedInterfaces = AopProxyUtils.completeProxiedInterfaces(this.advised, true);
			findDefinedEqualsAndHashCodeMethods(proxiedInterfaces);
			//这里已经看到jdk的动态代理了 
			//最后一个参数this 其本身就是一个InvocationHandler
			//继续跟他的invoke方法
			return Proxy.newProxyInstance(classLoader, proxiedInterfaces, this);
		}
		
	//invoke方法
	public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
		Object oldProxy = null;
		boolean setProxyContext = false;

		TargetSource targetSource = this.advised.targetSource;
		Object target = null;

		try {
			...省略代码
			Object retVal;
			// Get as late as possible to minimize the time we "own" the target,
			// in case it comes from a pool.
			target = targetSource.getTarget();
			Class targetClass = (target != null ? target.getClass() : null);

			// Get the interception chain for this method.
			//获取一个链 链中的每一个元素是目标方法的一个增强方法advice
			List chain = this.advised.getInterceptorsAndDynamicInterceptionAdvice(method, targetClass);

			//如果链是空的 直接执行目标方法
			if (chain.isEmpty()) {
				Object[] argsToUse = AopProxyUtils.adaptArgumentsIfNecessary(method, args);
				//直接执行目标方法
				retVal = AopUtils.invokeJoinpointUsingReflection(target, method, argsToUse);
			}
			else {
				//否则生成一个MethodInvocation对象
				//委托MethodInvocation  执行proceed方法来执行chain中的增强方法 完成方法增强
				MethodInvocation invocation =
						new ReflectiveMethodInvocation(proxy, target, method, args, targetClass, chain);
				// Proceed to the joinpoint through the interceptor chain.
				retVal = invocation.proceed();
			}
			...省略代码
			return retVal;
		}
		finally {
			...省略代码
		}
	}

}	
 

这里有两个分支
1 生成增强方法执行链 this.advised.getInterceptorsAndDynamicInterceptionAdvice
2 调用增强方法执行链 invocation.proceed()

4.2.2.1、生成增强方法执行链

跟getInterceptorsAndDynamicInterceptionAdvice
回到了AdvisedSupport类,该类除了封装了所有的advisior对象还提供了一些处理方法

public class AdvisedSupport extends ProxyConfig implements Advised {
	//一个专门创建增强执行链的工厂 最终会委托该类进行处理	
	AdvisorChainFactory advisorChainFactory = new DefaultAdvisorChainFactory();

	public List getInterceptorsAndDynamicInterceptionAdvice(Method method, @Nullable Class targetClass) {
			//外层是一个缓存机制
			MethodCacheKey cacheKey = new MethodCacheKey(method);
			List cached = this.methodCache.get(cacheKey);
			if (cached == null) {
				//主要流程在这里
				cached = this.advisorChainFactory.getInterceptorsAndDynamicInterceptionAdvice(
						this, method, targetClass);
				this.methodCache.put(cacheKey, cached);
			}
			return cached;
		}
}
 

跟 getInterceptorsAndDynamicInterceptionAdvice

public class DefaultAdvisorChainFactory implements AdvisorChainFactory, Serializable {
	//该方法主要有两个作用
	//1 匹配出所有和当前方法匹配的advisor
	//2 将advisor适配从MethodInterceptor对象
	//最终返回MethodInterceptor集合
	public List getInterceptorsAndDynamicInterceptionAdvice(
				Advised config, Method method, @Nullable Class targetClass) {
	
			//获取一个适配器 用于将advisor转化为MethodInterceptor对象
			//转化的目的是MethodInterceptor对象可以保证advisor中advice的执行顺序
			AdvisorAdapterRegistry registry = GlobalAdvisorAdapterRegistry.getInstance();
			//获取所有的advisors 
			Advisor[] advisors = config.getAdvisors();
			//用于保存结果的集合
			List interceptorList = new ArrayList<>(advisors.length);
			Class actualClass = (targetClass != null ? targetClass : method.getDeclaringClass());
			Boolean hasIntroductions = null;
	
			for (Advisor advisor : advisors) {
			    //一般advisor都是PointcutAdvisor类型的 所以重点看这里
				if (advisor instanceof PointcutAdvisor) {
					// Add it conditionally.
					PointcutAdvisor pointcutAdvisor = (PointcutAdvisor) advisor;
					if (config.isPreFiltered() || pointcutAdvisor.getPointcut().getClassFilter().matches(actualClass)) {
						//这里主要匹配出 方法对应的增强方法
						MethodMatcher mm = pointcutAdvisor.getPointcut().getMethodMatcher();
						boolean match;
						if (mm instanceof IntroductionAwareMethodMatcher) {
							if (hasIntroductions == null) {
								hasIntroductions = hasMatchingIntroductions(advisors, actualClass);
							}
							match = ((IntroductionAwareMethodMatcher) mm).matches(method, actualClass, hasIntroductions);
						}
						else {
							match = mm.matches(method, actualClass);
						}
						//如果方法与当前增强方法匹配
						if (match) {
							//这里对advisor做了转化 转化成MethodInterceptor
							//其实是将advisor里的advice转化成MethodInterceptor
							MethodInterceptor[] interceptors = registry.getInterceptors(advisor);
							//如果目标对象有重载方法 这里会做一个动态参数匹配
							if (mm.isRuntime()) {
								// Creating a new object instance in the getInterceptors() method
								// isn't a problem as we normally cache created chains.
								for (MethodInterceptor interceptor : interceptors) {
									interceptorList.add(new InterceptorAndDynamicMethodMatcher(interceptor, mm));
								}
							}
							//将转化结果封装到结果集中
							else {
								interceptorList.addAll(Arrays.asList(interceptors));
							}
						}
					}
				}
				else if (advisor instanceof IntroductionAdvisor) {
					...省略代码
				}
				else {
					...省略代码
				}
			}
	
			return interceptorList;
		}
}	
 
4.2.2.2、调用增强方法执行链 

回到刚刚的流程 跟invocation.proceed() 这里开始对方法进行增强了

public class ReflectiveMethodInvocation implements ProxyMethodInvocation, Cloneable {
	//构造器
	protected ReflectiveMethodInvocation(
			Object proxy, @Nullable Object target, Method method, @Nullable Object[] arguments,
			@Nullable Class targetClass, List interceptorsAndDynamicMethodMatchers) {
		//代理对象
		this.proxy = proxy;
		//目标对象
		this.target = target;
		//目标类 类型
		this.targetClass = targetClass;
		//目标方法
		this.method = BridgeMethodResolver.findBridgedMethod(method);
		//方法参数
		this.arguments = AopProxyUtils.adaptArgumentsIfNecessary(method, arguments);
		// 增强链【MethodInvocation集合】 上一步产生的结果
		this.interceptorsAndDynamicMethodMatchers = interceptorsAndDynamicMethodMatchers;
	}
	//执行增强链
	public Object proceed() throws Throwable {
			// We start with an index of -1 and increment early.
			//最终的MethodInterceptor集合都封装在了interceptorsAndDynamicMethodMatchers中
			//如果链都被执行完了 直接调用目标方法
			if (this.currentInterceptorIndex == this.interceptorsAndDynamicMethodMatchers.size() - 1) {
				return invokeJoinpoint();
			}
			//获取链中的下一个MethodInterceptor
			Object interceptorOrInterceptionAdvice =
					this.interceptorsAndDynamicMethodMatchers.get(++this.currentInterceptorIndex);
			//重载方法处理的这块 暂时先忽略不看了		
			if (interceptorOrInterceptionAdvice instanceof InterceptorAndDynamicMethodMatcher) {
				...省略代码
			}
			else {
				//最后执行MethodInterceptor的invoke方法
				return ((MethodInterceptor) interceptorOrInterceptionAdvice).invoke(this);
			}
		}
}	
 

可以看到链中执行了每一个MethodInterceptor的invoke方法
那么MethodInterceptor是如何保证执行顺序的?首先需要知道有几种MethodInterceptor
第一 基于生成advice的工厂ReflectiveAspectJAdvisorFactory类中可以知道,一共有5中advice
第二 通过了解AdvisorAdapterRegistry适配器 可以知道有两个advice被适配成了MethodInterceptor
也就是一共有五种MethodInterceptor,三个是原来的advice,两个是适配后的MethodInterceptor

下面列出了五种MethodInterceptor,以及其invoke方法

1 AfterReturningAdviceInterceptor 后置处理 适配得到的

public class AfterReturningAdviceInterceptor implements MethodInterceptor, AfterAdvice, Serializable {

	private final AfterReturningAdvice advice;


	
	public AfterReturningAdviceInterceptor(AfterReturningAdvice advice) {
		Assert.notNull(advice, "Advice must not be null");
		this.advice = advice;
	}


	@Override
	public Object invoke(MethodInvocation mi) throws Throwable {
		//这里可以看到先继续调用执行链 然后在执行自己的方法
		//保证了后置处理放到后边执行
		Object retVal = mi.proceed();
		this.advice.afterReturning(retVal, mi.getMethod(), mi.getArguments(), mi.getThis());
		return retVal;
	}

}

2 MethodBeforeAdviceInterceptor 适配得到的

public class MethodBeforeAdviceInterceptor implements MethodInterceptor, BeforeAdvice, Serializable {

	private final MethodBeforeAdvice advice;


	
	public MethodBeforeAdviceInterceptor(MethodBeforeAdvice advice) {
		Assert.notNull(advice, "Advice must not be null");
		this.advice = advice;
	}


	@Override
	public Object invoke(MethodInvocation mi) throws Throwable {
	    //这里可以看到先执行自己的方法 在调用执行链
		//保证了前置处理先执行
		this.advice.before(mi.getMethod(), mi.getArguments(), mi.getThis());
		return mi.proceed();
	}

}

3 AspectJAfterAdvice 强转得到的

public class AspectJAfterAdvice extends AbstractAspectJAdvice
		implements MethodInterceptor, AfterAdvice, Serializable {

	public AspectJAfterAdvice(
			Method aspectJBeforeAdviceMethod, AspectJExpressionPointcut pointcut, AspectInstanceFactory aif) {

		super(aspectJBeforeAdviceMethod, pointcut, aif);
	}


	@Override
	public Object invoke(MethodInvocation mi) throws Throwable {
		//把处理放到了finally里
		//保证最终的执行,无论是否抛出异常
		try {
			return mi.proceed();
		}
		finally {
			invokeAdviceMethod(getJoinPointMatch(), null, null);
		}
	}

	@Override
	public boolean isBeforeAdvice() {
		return false;
	}

	@Override
	public boolean isAfterAdvice() {
		return true;
	}

}

4 AspectJAfterThrowingAdvice 强转得到的

public class AspectJAfterThrowingAdvice extends AbstractAspectJAdvice
		implements MethodInterceptor, AfterAdvice, Serializable {

	public AspectJAfterThrowingAdvice(
			Method aspectJBeforeAdviceMethod, AspectJExpressionPointcut pointcut, AspectInstanceFactory aif) {

		super(aspectJBeforeAdviceMethod, pointcut, aif);
	}


	@Override
	public boolean isBeforeAdvice() {
		return false;
	}

	@Override
	public boolean isAfterAdvice() {
		return true;
	}

	@Override
	public void setThrowingName(String name) {
		setThrowingNameNoCheck(name);
	}

	@Override
	public Object invoke(MethodInvocation mi) throws Throwable {
		//这里保证了只有异常才会执行
		try {
			return mi.proceed();
		}
		catch (Throwable ex) {
			if (shouldInvokeOnThrowing(ex)) {
				invokeAdviceMethod(getJoinPointMatch(), null, ex);
			}
			throw ex;
		}
	}

	
	private boolean shouldInvokeOnThrowing(Throwable ex) {
		return getDiscoveredThrowingType().isAssignableFrom(ex.getClass());
	}

}

5 AspectJAroundAdvice 强转得到的

public class AspectJAroundAdvice extends AbstractAspectJAdvice implements MethodInterceptor, Serializable {

	public AspectJAroundAdvice(
			Method aspectJAroundAdviceMethod, AspectJExpressionPointcut pointcut, AspectInstanceFactory aif) {

		super(aspectJAroundAdviceMethod, pointcut, aif);
	}


	@Override
	public boolean isBeforeAdvice() {
		return false;
	}

	@Override
	public boolean isAfterAdvice() {
		return false;
	}

	@Override
	protected boolean supportsProceedingJoinPoint() {
		return true;
	}

	@Override
	public Object invoke(MethodInvocation mi) throws Throwable {
		if (!(mi instanceof ProxyMethodInvocation)) {
			throw new IllegalStateException("MethodInvocation is not a Spring ProxyMethodInvocation: " + mi);
		}
		ProxyMethodInvocation pmi = (ProxyMethodInvocation) mi;
		ProceedingJoinPoint pjp = lazyGetProceedingJoinPoint(pmi);
		JoinPointMatch jpm = getJoinPointMatch(pmi);
		//这里把调用联封装成了一个ProceedingJoinPoint对象交给增强方法来执行 这样更加灵活
		return invokeAdviceMethod(pjp, jpm, null, null);
	}

	
	protected ProceedingJoinPoint lazyGetProceedingJoinPoint(ProxyMethodInvocation rmi) {
		return new MethodInvocationProceedingJoinPoint(rmi);
	}

AroundAdvice把MethodInvocation以ProceedingJoinPoint形式暴露给了增强方法
增强方法可以自定义完成其他四种advice的写法。因为其持有MethodInvocation对象 最终可以调用ethodInvocation.proceed重回到调用链中
//例如下面的一个环绕增强方法

//相当于MethodBeforeAdviceInterceptor
public void myAroundAdvice(ProceedingJoinPoint pjp) throws Throwable {
		System.out.println("MethodBeforeAdviceInterceptor do some");
		try{
			//这样写挡墙与一个前置处理器
			pjp.proceed();
		}
	}
	
//相当于AfterReturningAdviceInterceptor
public void myAroundAdvice(ProceedingJoinPoint pjp) throws Throwable {
		pjp.proceed();
		System.out.println("AfterReturningAdviceInterceptor do some");
	}

//相当于AspectJAfterAdvice 
public void myAroundAdvice(ProceedingJoinPoint pjp) throws Throwable {
		try{
			pjp.proceed();
		}finally {
			System.out.println("AspectJAfterAdvice do some");
		}
	}
//相当于AspectJAfterThrowingAdvice	
public void myAroundAdvice(ProceedingJoinPoint pjp) throws Throwable {
		try{
			pjp.proceed();
		}catch (Throwable ex) {
			System.out.println("MethodBeforeAdviceInterceptor do some");
			throw ex;
		}
	}

roundAdvice应该是相对其他的几种更加灵活的advice

执行顺序总结
两种情况
一 AspectJAroundAdvice不存在时
1 MethodBeforeAdviceInterceptor 先执行
2 AfterReturningAdviceInterceptor 后执行-如果没有异常
3 AspectJAfterThrowingAdvice 后执行-如果有异常
4 AspectJAfterAdvice 最后执行

二 AspectJAroundAdvice存在时
AspectJAroundAdvice比较特别可以在执行链前后都加处理方法。将其称为around的前置后后置方法。
如果AspectJAroundAdvice在处理链中的位置比MethodBeforeAdviceInterceptor 靠前,那么around的前置方法比MethodBeforeAdviceInterceptor 的先执行,反之后执行。
如果AspectJAroundAdvice在处理链中的位置比AfterReturningAdviceInterceptor靠前,那么around的后置方法比AfterReturningAdviceInterceptor的先执行,反之后执行。


总结

整体流程梳理
1 找AOP入口
2 bean方法初始化后置处理中,获取bean对应的所有增强方法
3 基于增强方法生成代理对象(动态代理机制)

转载请注明:文章转载自 www.mshxw.com
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号