spring源码系列---AOP

@EnableAspectJAutoProxy 开启aop

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Import(AspectJAutoProxyRegistrar.class)
public @interface EnableAspectJAutoProxy {

	/**
	 * Indicate whether subclass-based (CGLIB) proxies are to be created as opposed
	 * to standard Java interface-based proxies. The default is {@code false}.
	 */
	boolean proxyTargetClass() default false;

	/**
	 * Indicate that the proxy should be exposed by the AOP framework as a {@code ThreadLocal}
	 * for retrieval via the {@link org.springframework.aop.framework.AopContext} class.
	 * Off by default, i.e. no guarantees that {@code AopContext} access will work.
	 * @since 4.3.1
	 */
	boolean exposeProxy() default false;

}

org.springframework.context.annotation.AspectJAutoProxyRegistrar

class AspectJAutoProxyRegistrar implements ImportBeanDefinitionRegistrar {

	/**
	 * Register, escalate, and configure the AspectJ auto proxy creator based on the value
	 * of the @{@link EnableAspectJAutoProxy#proxyTargetClass()} attribute on the importing
	 * {@code @Configuration} class.
	 */
	@Override
	public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {

		// 这里注册了AnnotationAwareAspectJAutoProxyCreator
		AopConfigUtils.registerAspectJAnnotationAutoProxyCreatorIfNecessary(registry);

		AnnotationAttributes enableAspectJAutoProxy =
				AnnotationConfigUtils.attributesFor(importingClassMetadata, EnableAspectJAutoProxy.class);
		if (enableAspectJAutoProxy != null) {
			if (enableAspectJAutoProxy.getBoolean("proxyTargetClass")) {
				AopConfigUtils.forceAutoProxyCreatorToUseClassProxying(registry);
			}
			if (enableAspectJAutoProxy.getBoolean("exposeProxy")) {
				AopConfigUtils.forceAutoProxyCreatorToExposeProxy(registry);
			}
		}
	}
}

org.springframework.aop.config.AopConfigUtils#registerAspectJAnnotationAutoProxyCreatorIfNecessary

public static BeanDefinition registerAspectJAnnotationAutoProxyCreatorIfNecessary(
			BeanDefinitionRegistry registry, @Nullable Object source) {

		// AopConfigUtil.registerAspectJAnnotationAutoProxyCreatorIfNecessary方法实现中,会直接将AspectJAwareAdvisorAutoProxyCreator注册到BeanFactory中
		return registerOrEscalateApcAsRequired(AnnotationAwareAspectJAutoProxyCreator.class, registry, source);
	}

注意看这里注册的 AnnotationAwareAspectJAutoProxyCreator

SmartInstantiationAwareBeanPostProcessor继承InstantiationAwareBeanPostProcessor 具有Bean的前置和后置的处理器功能,所以AbstractAutoProxyCreator 实例化后会执行它的 postProcessAfterInitialization。到这里开启aop的工作算是完成了


org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#initializeBean 实例化bean,不知道的可以看你spring启动的那篇文章

protected Object initializeBean(String beanName, Object bean, @Nullable RootBeanDefinition mbd) {
		if (System.getSecurityManager() != null) {
			AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
				invokeAwareMethods(beanName, bean);
				return null;
			}, getAccessControlContext());
		}
		else {
			// 5、执行Aware
			invokeAwareMethods(beanName, bean);
		}

		Object wrappedBean = bean;
		if (mbd == null || !mbd.isSynthetic()) {
			// 6、执行初始化前
			// 某些特殊方法的调用 @PostConstruct,Aware接口
			// 调用BeanPostProcessor的postProcessBeforeInitialization方法
			wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
		}

		try {
			// 7、执行初始化
			// controller处理入口
			// InitializingBean接口,afterPropertiesSet方法和init-method属性调用
			// 如果bean实现了InitializingBean接口,那么会直接调用afterPropertiesSet方法
			// 如果<bean>节点中配置了init-method,会通过反射调用init-method指定的方法
			invokeInitMethods(beanName, wrappedBean, mbd);
		}
		catch (Throwable ex) {
			throw new BeanCreationException(
					(mbd != null ? mbd.getResourceDescription() : null),
					beanName, "Invocation of init method failed", ex);
		}

		// Aop入口,有切面的实例才会被代理
		if (mbd == null || !mbd.isSynthetic()) {
			// 8、执行初始化后
			// 调用BeanPostProcessor的postProcessAfterInitialization方法
			wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
		}

		return wrappedBean;
	}

org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#applyBeanPostProcessorsAfterInitialization 直接看初始化后

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

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

org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator#postProcessAfterInitialization 执行初始化后的后置处理器

public Object postProcessAfterInitialization(@Nullable Object bean, String beanName) {
		if (bean != null) {
			// 缓存键:1.beanName不为空的话,使用beanName(FactoryBean会在见面加上"&")
			// 2.如果beanName为空,使用Class对象作为缓存的key
			Object cacheKey = getCacheKey(bean.getClass(), beanName);
			if (this.earlyProxyReferences.remove(cacheKey) != bean) {
				// 如果条件符合,则为bean生成代理对象
				return wrapIfNecessary(bean, beanName, cacheKey);
			}
		}
		return bean;
	}

org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator#wrapIfNecessary

protected Object wrapIfNecessary(Object bean, String beanName, Object cacheKey) {
		// 如果已经处理过(targetSourcedBeans存放已经增强过的bean)
		if (StringUtils.hasLength(beanName) && this.targetSourcedBeans.contains(beanName)) {
			return bean;
		}

		// advisedBeans的key为cacheKey,value为boolean类型,表示是否进行过代理
		// 已经处理过的bean,不需要再次进行处理,节省时间
		if (Boolean.FALSE.equals(this.advisedBeans.get(cacheKey))) {
			return bean;
		}

		// 是否是继承自Advice、Pointcut、Advisor、AopInfrastructureBean || 配置了指定bean不需要代理
		if (isInfrastructureClass(bean.getClass()) || shouldSkip(bean.getClass(), beanName)) {
			this.advisedBeans.put(cacheKey, Boolean.FALSE);
			return bean;
		}

		// 获取特定的拦截器,也就是所有适用的Advisor
		// Create proxy if we have advice.
		Object[] specificInterceptors = getAdvicesAndAdvisorsForBean(bean.getClass(), beanName, null);

		// 如果获取的增强不为null,则为该bean创建代理(DO_NOT_PROXY=null)
		if (specificInterceptors != DO_NOT_PROXY) {
			this.advisedBeans.put(cacheKey, Boolean.TRUE);
			// 配置ProxyFactory
			Object proxy = createProxy(bean.getClass(), beanName, specificInterceptors, new SingletonTargetSource(bean));
			this.proxyTypes.put(cacheKey, proxy.getClass());
			return proxy;
		}

		// 标记该cacheKey已经被处理过
		this.advisedBeans.put(cacheKey, Boolean.FALSE);
		return bean;
	}

org.springframework.aop.framework.autoproxy.AbstractAdvisorAutoProxyCreator#getAdvicesAndAdvisorsForBean 获取需要被代理的类

protected Object[] getAdvicesAndAdvisorsForBean(
			Class<?> beanClass, String beanName, @Nullable TargetSource targetSource) {

		// 从beanDefinitionNames中找到所有合格的Advisors
		List<Advisor> advisors = findEligibleAdvisors(beanClass, beanName);
		if (advisors.isEmpty()) {
			return DO_NOT_PROXY;
		}
		return advisors.toArray();
	}

org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator#createProxy

protected Object createProxy(Class<?> beanClass, @Nullable String beanName,
			@Nullable Object[] specificInterceptors, TargetSource targetSource) {

		// 在bean对应的BeanDefinition中添加原Class对象属性(保存bean原本的Class)
		if (this.beanFactory instanceof ConfigurableListableBeanFactory) {
			AutoProxyUtils.exposeTargetClass((ConfigurableListableBeanFactory) this.beanFactory, beanName, beanClass);
		}

		ProxyFactory proxyFactory = new ProxyFactory();

		// 获取当前类中配置的属性
		proxyFactory.copyFrom(this);

		// 检查proxyTargetClass属性
		if (!proxyFactory.isProxyTargetClass()) {
			// 检查beanDefinitioin中是否包含preserveTargetClass属性,且属性为true
			// 设置是否使用CGLib进行代理
			if (shouldProxyTargetClass(beanClass, beanName)) {
				proxyFactory.setProxyTargetClass(true);
			}
			else {
				// 筛选代理接口并添加到proxyFactory
				evaluateProxyInterfaces(beanClass, proxyFactory);
			}
		}

		// 获取增强器(包括前面筛选出来的Advice,以及通过setInterceptorNames中添加的通用增强器,默认为空)
		Advisor[] advisors = buildAdvisors(beanName, specificInterceptors);

		// 将所有增强器添加到proxyFactor
		proxyFactory.addAdvisors(advisors);

		// 设置需要代理的bean对象信息
		proxyFactory.setTargetSource(targetSource);

		// 模版方法,由子类定制化代理
		customizeProxyFactory(proxyFactory);

		// 用来控制代理工程被配置后,是否还允许修改代理的配置,默认为false
		proxyFactory.setFrozen(this.freezeProxy);
		if (advisorsPreFiltered()) {
			proxyFactory.setPreFiltered(true);
		}

		// 创建代理对象
		return proxyFactory.getProxy(getProxyClassLoader());
	}

org.springframework.aop.framework.ProxyFactory#getProxy 选择jdk动态代理还是Cglib

public Object getProxy(@Nullable ClassLoader classLoader) {
		return createAopProxy().getProxy(classLoader);
	}

org.springframework.aop.framework.CglibAopProxy#getProxy 这里以Cglib为例

public Object getProxy(@Nullable ClassLoader classLoader) {
		if (logger.isTraceEnabled()) {
			logger.trace("Creating CGLIB proxy: " + this.advised.getTargetSource());
		}

		try {
			Class<?> rootClass = this.advised.getTargetClass();
			Assert.state(rootClass != null, "Target class must be available for creating a CGLIB proxy");

			Class<?> proxySuperClass = rootClass;
			if (rootClass.getName().contains(ClassUtils.CGLIB_CLASS_SEPARATOR)) {
				proxySuperClass = rootClass.getSuperclass();
				Class<?>[] additionalInterfaces = rootClass.getInterfaces();
				for (Class<?> additionalInterface : additionalInterfaces) {
					this.advised.addInterface(additionalInterface);
				}
			}

			// Validate the class, writing log messages as necessary.
			validateClassIfNecessary(proxySuperClass, classLoader);

			// Configure CGLIB Enhancer...
			Enhancer enhancer = createEnhancer();
			if (classLoader != null) {
				enhancer.setClassLoader(classLoader);
				if (classLoader instanceof SmartClassLoader &&
						((SmartClassLoader) classLoader).isClassReloadable(proxySuperClass)) {
					enhancer.setUseCache(false);
				}
			}
			enhancer.setSuperclass(proxySuperClass);
			enhancer.setInterfaces(AopProxyUtils.completeProxiedInterfaces(this.advised));
			enhancer.setNamingPolicy(SpringNamingPolicy.INSTANCE);
			enhancer.setStrategy(new ClassLoaderAwareGeneratorStrategy(classLoader));

			// 设置拦截器回调:DynamicAdvisedInterceptor,所以会执行他的intercept方法
			Callback[] callbacks = getCallbacks(rootClass);
			Class<?>[] types = new Class<?>[callbacks.length];
			for (int x = 0; x < types.length; x++) {
				types[x] = callbacks[x].getClass();
			}

			// 仅在上述getCallbacks调用之后,此时才会填充fixedInterceptorMap
			// fixedInterceptorMap only populated at this point, after getCallbacks call above
			enhancer.setCallbackFilter(new ProxyCallbackFilter(
					this.advised.getConfigurationOnlyCopy(), this.fixedInterceptorMap, this.fixedInterceptorOffset));
			enhancer.setCallbackTypes(types);

			// 生成代理类并创建代理实例
			// Generate the proxy class and create a proxy instance.
			return createProxyClassAndInstance(enhancer, callbacks);
		}
		catch (CodeGenerationException | IllegalArgumentException ex) {
			throw new AopConfigException("Could not generate CGLIB subclass of " + this.advised.getTargetClass() +
					": Common causes of this problem include using a final class or a non-visible class",
					ex);
		}
		catch (Throwable ex) {
			// TargetSource.getTarget() failed
			throw new AopConfigException("Unexpected AOP exception", ex);
		}
	}

org.springframework.aop.framework.CglibAopProxy#getCallbacks 设置回调

private Callback[] getCallbacks(Class<?> rootClass) throws Exception {
		// 用于优化选择的参数
		// Parameters used for optimization choices...
		boolean exposeProxy = this.advised.isExposeProxy();
		boolean isFrozen = this.advised.isFrozen();
		boolean isStatic = this.advised.getTargetSource().isStatic();

		// 选择一个“ aop”拦截器(用于AOP回调)
		// Choose an "aop" interceptor (used for AOP calls).
		Callback aopInterceptor = new DynamicAdvisedInterceptor(this.advised);

		// Choose a "straight to target" interceptor. (used for calls that are
		// unadvised but can return this). May be required to expose the proxy.
		Callback targetInterceptor;
		if (exposeProxy) {
			targetInterceptor = (isStatic ?
					new StaticUnadvisedExposedInterceptor(this.advised.getTargetSource().getTarget()) :
					new DynamicUnadvisedExposedInterceptor(this.advised.getTargetSource()));
		}
		else {
			targetInterceptor = (isStatic ?
					new StaticUnadvisedInterceptor(this.advised.getTargetSource().getTarget()) :
					new DynamicUnadvisedInterceptor(this.advised.getTargetSource()));
		}

		// Choose a "direct to target" dispatcher (used for
		// unadvised calls to static targets that cannot return this).
		Callback targetDispatcher = (isStatic ?
				new StaticDispatcher(this.advised.getTargetSource().getTarget()) : new SerializableNoOp());

		Callback[] mainCallbacks = new Callback[] {
				aopInterceptor,  // for normal advice
				targetInterceptor,  // invoke target without considering advice, if optimized
				new SerializableNoOp(),  // no override for methods mapped to this
				targetDispatcher, this.advisedDispatcher,
				new EqualsInterceptor(this.advised),
				new HashCodeInterceptor(this.advised)
		};

		Callback[] callbacks;

		// If the target is a static one and the advice chain is frozen,
		// then we can make some optimizations by sending the AOP calls
		// direct to the target using the fixed chain for that method.
		if (isStatic && isFrozen) {
			Method[] methods = rootClass.getMethods();
			Callback[] fixedCallbacks = new Callback[methods.length];
			this.fixedInterceptorMap = new HashMap<>(methods.length);

			// TODO: small memory optimization here (can skip creation for methods with no advice)
			for (int x = 0; x < methods.length; x++) {
				Method method = methods[x];
				List<Object> chain = this.advised.getInterceptorsAndDynamicInterceptionAdvice(method, rootClass);
				fixedCallbacks[x] = new FixedChainStaticTargetInterceptor(
						chain, this.advised.getTargetSource().getTarget(), this.advised.getTargetClass());
				this.fixedInterceptorMap.put(method, x);
			}

			// Now copy both the callbacks from mainCallbacks
			// and fixedCallbacks into the callbacks array.
			callbacks = new Callback[mainCallbacks.length + fixedCallbacks.length];
			System.arraycopy(mainCallbacks, 0, callbacks, 0, mainCallbacks.length);
			System.arraycopy(fixedCallbacks, 0, callbacks, mainCallbacks.length, fixedCallbacks.length);
			this.fixedInterceptorOffset = mainCallbacks.length;
		}
		else {
			callbacks = mainCallbacks;
		}
		return callbacks;
	}
// 实现了MethodInterceptor;代理类会经过并执行intercept方法
private static class DynamicAdvisedInterceptor implements MethodInterceptor, Serializable

org.springframework.aop.framework.CglibAopProxy.DynamicAdvisedInterceptor#intercept

public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
			Object oldProxy = null;
			boolean setProxyContext = false;
			Object target = null;
			TargetSource targetSource = this.advised.getTargetSource();
			try {
				if (this.advised.exposeProxy) {
					// Make invocation available if necessary.
					oldProxy = AopContext.setCurrentProxy(proxy);
					setProxyContext = true;
				}
				// 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);

				// 将得到的所有匹配的MethodInterception组合成调用连chain
				List<Object> chain = this.advised.getInterceptorsAndDynamicInterceptionAdvice(method, targetClass);
				Object retVal;
				// Check whether we only have one InvokerInterceptor: that is,
				// no real advice, but just reflective invocation of the target.
				if (chain.isEmpty() && Modifier.isPublic(method.getModifiers())) {
					// We can skip creating a MethodInvocation: just invoke the target directly.
					// Note that the final invoker must be an InvokerInterceptor, so we know
					// it does nothing but a reflective operation on the target, and no hot
					// swapping or fancy proxying.
					Object[] argsToUse = AopProxyUtils.adaptArgumentsIfNecessary(method, args);
					retVal = methodProxy.invoke(target, argsToUse);
				}
				else {
					// 将代理对象、被代理对象、当前正在执行的被代理类中的方法对象、方法参数、被代理的类、chain整合成一个CglibMethodInvocation,然后调用他的proceed方法
					// We need to create a method invocation...
					retVal = new CglibMethodInvocation(proxy, target, method, args, targetClass, chain, methodProxy).proceed();
				}
				retVal = processReturnType(proxy, target, method, retVal);
				return retVal;
			}
			finally {
				if (target != null && !targetSource.isStatic()) {
					targetSource.releaseTarget(target);
				}
				if (setProxyContext) {
					// Restore old proxy.
					AopContext.setCurrentProxy(oldProxy);
				}
			}
		}

org.springframework.aop.framework.AdvisedSupport#getInterceptorsAndDynamicInterceptionAdvice 将得到的MethodInterceptor组合成List<Object> chain

public List<Object> getInterceptorsAndDynamicInterceptionAdvice(Method method, @Nullable Class<?> targetClass) {
		// 缓存的cacheKey,先尝试从缓存获取,不存在再从ProxyFactory中解析
		MethodCacheKey cacheKey = new MethodCacheKey(method);
		List<Object> cached = this.methodCache.get(cacheKey);
		if (cached == null) {
			// 通过实例方法和ProxyFactory中保存的信息,解析出匹配的增强
			cached = this.advisorChainFactory.getInterceptorsAndDynamicInterceptionAdvice(
					this, method, targetClass);
			this.methodCache.put(cacheKey, cached);
		}
		return cached;
	}

org.springframework.aop.framework.DefaultAdvisorChainFactory#getInterceptorsAndDynamicInterceptionAdvice

public List<Object> getInterceptorsAndDynamicInterceptionAdvice(
			Advised config, Method method, @Nullable Class<?> targetClass) {

		// This is somewhat tricky... We have to process introductions first,
		// but we need to preserve order in the ultimate list.
		AdvisorAdapterRegistry registry = GlobalAdvisorAdapterRegistry.getInstance();

		// 根据当前调用的类获取对应的Advisor
		Advisor[] advisors = config.getAdvisors();
		List<Object> interceptorList = new ArrayList<>(advisors.length);
		Class<?> actualClass = (targetClass != null ? targetClass : method.getDeclaringClass());
		Boolean hasIntroductions = null;

		// 遍历增强器
		for (Advisor advisor : advisors) {
			// PointcutAdvisor类型的增强器
			// 通过@Aspect加入的增强器类型为InstantiationModelAwarePointcutAdvisorImpl,实现了PointcutAdvisor
			if (advisor instanceof PointcutAdvisor) {
				// Add it conditionally.
				PointcutAdvisor pointcutAdvisor = (PointcutAdvisor) advisor;
				if (config.isPreFiltered() || pointcutAdvisor.getPointcut().getClassFilter().matches(actualClass)) {
					// 通过他先筛选Advisor
					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中的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) {
				IntroductionAdvisor ia = (IntroductionAdvisor) advisor;
				if (config.isPreFiltered() || ia.getClassFilter().matches(actualClass)) {
					Interceptor[] interceptors = registry.getInterceptors(advisor);
					interceptorList.addAll(Arrays.asList(interceptors));
				}
			}
			else {
				Interceptor[] interceptors = registry.getInterceptors(advisor);
				interceptorList.addAll(Arrays.asList(interceptors));
			}
		}

		return interceptorList;
	}

org.springframework.aop.framework.adapter.DefaultAdvisorAdapterRegistry#getInterceptors 获取Advisor中的Advice并封装为MethodInterceptor

public MethodInterceptor[] getInterceptors(Advisor advisor) throws UnknownAdviceTypeException {
		List<MethodInterceptor> interceptors = new ArrayList<>(3);

		// 获取Advice
		Advice advice = advisor.getAdvice();

		// 如果Advice实例同时已经实现MethodInterceptor接口,则直接使用
		if (advice instanceof MethodInterceptor) {
			interceptors.add((MethodInterceptor) advice);
		}

		// 需要使用适配器来转换Advice接口
		for (AdvisorAdapter adapter : this.adapters) {
			if (adapter.supportsAdvice(advice)) {
				interceptors.add(adapter.getInterceptor(advisor));
			}
		}
		if (interceptors.isEmpty()) {
			throw new UnknownAdviceTypeException(advisor.getAdvice());
		}
		return interceptors.toArray(new MethodInterceptor[0]);
	}

org.springframework.aop.framework.CglibAopProxy.CglibMethodInvocation#CglibMethodInvocation 将代理对象中的方法整合成CglibMethodInvocation对象,再调用proceed方法

org.springframework.aop.framework.ReflectiveMethodInvocation#proceed

public Object proceed() throws Throwable {
		//	执行完所有增强后,执行切点方法
		// We start with an index of -1 and increment early.
		if (this.currentInterceptorIndex == this.interceptorsAndDynamicMethodMatchers.size() - 1) {
			return invokeJoinpoint();
		}

		// 获取下一个拦截器
		Object interceptorOrInterceptionAdvice = this.interceptorsAndDynamicMethodMatchers.get(++this.currentInterceptorIndex);

		if (interceptorOrInterceptionAdvice instanceof InterceptorAndDynamicMethodMatcher) {

			// 动态匹配
			// Evaluate dynamic method matcher here: static part will already have
			// been evaluated and found to match.
			InterceptorAndDynamicMethodMatcher dm = (InterceptorAndDynamicMethodMatcher) interceptorOrInterceptionAdvice;

			Class<?> targetClass = (this.targetClass != null ? this.targetClass : this.method.getDeclaringClass());
			if (dm.methodMatcher.matches(this.method, targetClass, this.arguments)) {
				return dm.interceptor.invoke(this);
			}
			else {
				// 不匹配则不执行拦截器
				// Dynamic matching failed.
				// Skip this interceptor and invoke the next in the chain.
				return proceed();
			}
		}
		else {
			// 普通拦截器。比如:MethodBeforeAdviceInterceptor、AfterReturningAdviceInterceptor、ThrowsAdviceInterceptor
			// It's an interceptor, so we just invoke it: The pointcut will have
			// been evaluated statically before this object was constructed.
			return ((MethodInterceptor) interceptorOrInterceptionAdvice).invoke(this);
		}
	}

org.springframework.aop.framework.adapter.MethodBeforeAdviceInterceptor#invoke 开始执行MethodInterceptor#invoke,这里以@After为例

public Object invoke(MethodInvocation mi) throws Throwable {
		// 拦截器会在调用真正方法前,调用MethodBeforeAdvice的before方法,在这一步,也就完成了方法的前置增强。
		// AspectJMethodBeforeAdvice.before
		this.advice.before(mi.getMethod(), mi.getArguments(), mi.getThis());
		return mi.proceed();
	}

org.springframework.aop.aspectj.AspectJMethodBeforeAdvice#before

public void before(Method method, Object[] args, @Nullable Object target) throws Throwable {
		// 将参数绑定后,传入invokeAdviceMethodWithGivenArgs方法执行
		invokeAdviceMethod(getJoinPointMatch(), null, null);
	}

org.springframework.aop.aspectj.AbstractAspectJAdvice#invokeAdviceMethod

protected Object invokeAdviceMethod(
			@Nullable JoinPointMatch jpMatch, @Nullable Object returnValue, @Nullable Throwable ex)
			throws Throwable {

		return invokeAdviceMethodWithGivenArgs(argBinding(getJoinPoint(), jpMatch, returnValue, ex));
	}

org.springframework.aop.aspectj.AbstractAspectJAdvice#invokeAdviceMethodWithGivenArgs

protected Object invokeAdviceMethodWithGivenArgs(Object[] args) throws Throwable {
		Object[] actualArgs = args;

		// 如果advice增强方法参数为空
		if (this.aspectJAdviceMethod.getParameterCount() == 0) {
			actualArgs = null;
		}
		try {
			ReflectionUtils.makeAccessible(this.aspectJAdviceMethod);

			// 通过反射,调用增强方法
			// TODO AopUtils.invokeJoinpointUsingReflection
			return this.aspectJAdviceMethod.invoke(this.aspectInstanceFactory.getAspectInstance(), actualArgs);
		}
		catch (IllegalArgumentException ex) {
			throw new AopInvocationException("Mismatch on arguments to advice method [" +
					this.aspectJAdviceMethod + "]; pointcut expression [" +
					this.pointcut.getPointcutExpression() + "]", ex);
		}
		catch (InvocationTargetException ex) {
			throw ex.getTargetException();
		}
	}

 

贴一个流程分析步骤

@EnableAspectJAutoProxy
	@Import({AspectJAutoProxyRegistrar.class})
		AspectJAutoProxyRegistrar实现了ImportBeanDefinitionRegistrar
			registerBeanDefinitions
				AopConfigUtils.registerAspectJAnnotationAutoProxyCreatorIfNecessary 这里会注册AnnotationAwareAspectJAutoProxyCreator
					AnnotationAwareAspectJAutoProxyCreator父类继承了AbstractAutoProxyCreator,它又实现了SmartInstantiationAwareBeanPostProcessor
						SmartInstantiationAwareBeanPostProcessor继承InstantiationAwareBeanPostProcessor 具有Bean的前置和后置的处理器功能
							AbstractAutoProxyCreator 实例化后会执行它的 postProcessAfterInitialization
							
AbstractAutowireCapableBeanFactory#doCreateBean 上面设置并注册的bean的后置处理器,在bean实例化后会进行回调
	initializeBean
		applyBeanPostProcessorsAfterInitialization
			AbstractAutoProxyCreator#postProcessAfterInitialization 执行后置处理器
				AbstractAutoProxyCreator#wrapIfNecessary
					getAdvicesAndAdvisorsForBean 
						AbstractAdvisorAutoProxyCreator#getAdvicesAndAdvisorsForBean 获取需要被代理的类
						AbstractAutoProxyCreator#createProxy 配置ProxyFactory
							ProxyFactory#getProxy 选择jdk动态代理还是Cglib
								CglibAopProxy#getProxy 这里以Cglib为例
									Enhancer 构建Enhancer
										设置Callback为 DynamicAdvisedInterceptor,它实现了MethodInterceptor;代理类会经过并执行intercept方法
										
CglibAopProxy.DynamicAdvisedInterceptor#intercept	
	AdvisedSupport#getInterceptorsAndDynamicInterceptionAdvice
		DefaultAdvisorChainFactory#getInterceptorsAndDynamicInterceptionAdvice 
			MethodMatcher 通过他先筛选Advisor
				DefaultAdvisorAdapterRegistry#getInterceptors 获取Advisor中的Advice并封装为MethodInterceptor
					将得到的MethodInterceptor组合成List<Object> chain
						将代理对象中的方法整合成CglibMethodInvocation对象,再调用proceed方法
							new CglibAopProxy.CglibMethodInvocation().proceed() 
								开始执行MethodInterceptor#invoke
									AspectJAfterAdvice#invoke 这里以@After为例
										AbstractAspectJAdvice#invokeAdviceMethod 再执行代理对象的方法,也就是业务方法

 

总结一下:

1、开启aop的同时导入AspectJAutoProxyRegistrar,他初始化的时候内部注册了AnnotationAwareAspectJAutoProxyCreator,他的父类中继承InstantiationAwareBeanPostProcessor 具有Bean的前置和后置的处理器功能,因此实例化后会执行它的 postProcessAfterInitialization。

2、AbstractAutoProxyCreator初始化后执行后置处理器,首先找到需要被代理的类,根据实际情况确定jdk动态代理还是Cglib,最后设置回调方法DynamicAdvisedInterceptor,它实现了MethodInterceptor;代理类会经过并执行intercept方法。

3、执行过程中先筛选出代理类中的Advisor,再找出Advisor中的Advice并封装为MethodInterceptor,并得到调用的拦截器链,最后将代理对象中的方法整合成CglibMethodInvocation对象,再调用proceed方法,里面会执行拦截器的imvoke方法。

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值