[Spring]Spring AOP如何匹配合适的Advisor-getAdvicesAndAdvisorsForBean

前文回顾

在前面我们了解到了AnnotationAwareAspectJAutoProxyCreator是如何解析Aspect切面类成Advisor列表的,在解析完Advisors之后,Spring 就要开始对符合条件的Bean做”织入”操作了.

织入切面逻辑的入口

Spring AOP是在Bean的初始化过程中进行的,Spring Bean的生命周期从宏观上可以简单视为:
实例化->依赖注入->初始化->销毁.
在完成依赖注入之后,Spring会执行initializeBean方法对Bean做初始化:

  • org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#initializeBean
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 {
		// 激活BeanNameAware、BeanClassLoaderAware、BeanFactoryAware
		invokeAwareMethods(beanName, bean);
	}

	Object wrappedBean = bean;
	if (mbd == null || !mbd.isSynthetic()) {
		// 激活BeanPostProcessor的postProcessBeforeInitialization方法
		wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
	}

	try {
		// 激活InitializingBean的afterPropertiesSet方法、initMethod
		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()) {
		// 激活BeanPostProcessor的postProcessAfterInitialization方法
		wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
	}

	return wrappedBean;
}
复制代码

在执行完invokeInitMethods方法之后,Spring接着触发了BeanPostProcessorpostProcessAfterInitialization方法.

AnnotationAwareAspectJAutoProxyCreator继承自AbstractAutoProxyCreator,AbstractAutoProxyCreator又通过SmartInstantiationAwareBeanPostProcessor实现了BeanPostProcessor这个顶层接口.
因此,在applyBeanPostProcessorsAfterInitialization中会触发org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator#postProcessAfterInitialization.

wrapIfNecessary

  • org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator#postProcessAfterInitialization
public Object postProcessAfterInitialization(@Nullable Object bean, String beanName) {
	if (bean != null) {
		Object cacheKey = getCacheKey(bean.getClass(), beanName);
		// 当Bean被循环引用,并且被暴露了
		// 就会通过 getEarlyBeanReference来创建代理类
		// 通过判断 earlyProxyReferences 中是否存在beanName来决定是否需要对target类进行动态代理
		if (this.earlyProxyReferences.remove(cacheKey) != bean) {
			// 代理
			return wrapIfNecessary(bean, beanName, cacheKey);
		}
	}
	return bean;
}
复制代码

Spring在进行代理之前会判断Bean是否为空,如果不为空,那么会从缓存中查看当前Bean是否已经在之前被处理过了.
接着Spring还会查看一下earlyProxyReferences中是否存在当前bean,earlyProxyReferences是一个用来解决循环依赖的Map.
Spring处理正常Bean的织入都是在初始化后的,但是如果发生了循环依赖,Bean不得不提前暴露引用时,需要提前生成代理,此时在earlyProxyReferences中就会存放一个引用,证明当前的bean已经被提前暴露并代理了.

具体的逻辑在org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator#getEarlyBeanReference中.

  • org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator#wrapIfNecessary
protected Object wrapIfNecessary(Object bean, String beanName, Object cacheKey) {
	// beanName不为空,并且存在于targetSourcedBeans中,也就是自定义的TargetSource被解析过了
	if (StringUtils.hasLength(beanName) && this.targetSourcedBeans.contains(beanName)) {
		return bean;
	}
	// 如果Bean为advisedBeans,也不需要被代理
	if (Boolean.FALSE.equals(this.advisedBeans.get(cacheKey))) {
		return bean;
	}
	// isInfrastructureClass和shouldSkip的作用:
	// 识别切面类,加载切面类成advisors
	// 为什么又执行一次是因为存在循环依赖的情况下无法加载advisor
	if (isInfrastructureClass(bean.getClass()) || shouldSkip(bean.getClass(), beanName)) {
		this.advisedBeans.put(cacheKey, Boolean.FALSE);
		return bean;
	}

	// Create proxy if we have advice.
	// 返回匹配当前Bean的所有Advice、Advisor、Interceptor
	Object[] specificInterceptors = getAdvicesAndAdvisorsForBean(bean.getClass(), beanName, null);
	if (specificInterceptors != DO_NOT_PROXY) {
		this.advisedBeans.put(cacheKey, Boolean.TRUE);
		// 创建Bean对应的代理,SingletonTargetSource用于封装实现类的信息
		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. 判断缓存中是否存在当前Bean或者是当前Bean已经被代理过了,那么直接返回bean.
  2. 尝试再次加载advisor,避免由于循环依赖导致advisor加载不完整.
  3. 获取当前bean符合的advisor数组.
  4. 创建代理类.

本文来分析getAdvicesAndAdvisorsForBean方法是如何在所有的advisors中找到匹配的advisor的.

  • org.springframework.aop.framework.autoproxy.AbstractAdvisorAutoProxyCreator#getAdvicesAndAdvisorsForBean
protected Object[] getAdvicesAndAdvisorsForBean(
		Class<?> beanClass, String beanName, @Nullable TargetSource targetSource) {
	// eligible->合适的、合格的
	List<Advisor> advisors = findEligibleAdvisors(beanClass, beanName);
	if (advisors.isEmpty()) {
		return DO_NOT_PROXY;
	}
	return advisors.toArray();
}
复制代码

这里调用了findEligibleAdvisors来寻找合适的advisors,如果返回的集合为空,那么最后返回null.
如果返回了advisors,将其数组化返回.

  • org.springframework.aop.framework.autoproxy.AbstractAdvisorAutoProxyCreator#findEligibleAdvisors
protected List<Advisor> findEligibleAdvisors(Class<?> beanClass, String beanName) {
	// 找到之前加载过的所有候选advisors
	List<Advisor> candidateAdvisors = findCandidateAdvisors();
	// 判断找到的Advisor能不能作用到当前类上
	List<Advisor> eligibleAdvisors = findAdvisorsThatCanApply(candidateAdvisors, beanClass, beanName);
	extendAdvisors(eligibleAdvisors);
	// 对获取到的advisor进行排序
	if (!eligibleAdvisors.isEmpty()) {
		eligibleAdvisors = sortAdvisors(eligibleAdvisors);
	}
	return eligibleAdvisors;
}
复制代码
  1. 首先获取之前解析过的advisors列表-candidateAdvisors ,这里是所有的切面类解析成的advisors.
  2. candidateAdvisors中找到当前Bean匹配的advisor-findAdvisorsThatCanApply.
  3. 将获取到的eligibleAdvisors进行排序.
  • org.springframework.aop.framework.autoproxy.AbstractAdvisorAutoProxyCreator#findAdvisorsThatCanApply
protected List<Advisor> findAdvisorsThatCanApply(
		List<Advisor> candidateAdvisors, Class<?> beanClass, String beanName) {
	// 给currentProxiedBeanName这个ThreadLocal变量设置上正在动态代理的beanName
	ProxyCreationContext.setCurrentProxiedBeanName(beanName);
	try {
		// 筛选出匹配Bean的Advisors
		return AopUtils.findAdvisorsThatCanApply(candidateAdvisors, beanClass);
	}
	finally {
		ProxyCreationContext.setCurrentProxiedBeanName(null);
	}
}
复制代码

最终是调用了AopUtils.findAdvisorsThatCanApply来筛选匹配Bean的Advisors.

  • org.springframework.aop.support.AopUtils#findAdvisorsThatCanApply
public static List<Advisor> findAdvisorsThatCanApply(List<Advisor> candidateAdvisors, Class<?> clazz) {
	if (candidateAdvisors.isEmpty()) {
		return candidateAdvisors;
	}
	// 存储最终匹配的Advisor集合
	List<Advisor> eligibleAdvisors = new ArrayList<>();
	for (Advisor candidate : candidateAdvisors) {
		// 当前advisor对象是否实现了IntroductionAdvisor接口
		if (candidate instanceof IntroductionAdvisor && canApply(candidate, clazz)) {
			eligibleAdvisors.add(candidate);
		}
	}
	boolean hasIntroductions = !eligibleAdvisors.isEmpty();
	for (Advisor candidate : candidateAdvisors) {
		if (candidate instanceof IntroductionAdvisor) {
			// already processed
			continue;
		}
		// canApply->判断当前的advisor的pointcut表达式是否匹配当前class
		if (canApply(candidate, clazz, hasIntroductions)) {
			eligibleAdvisors.add(candidate);
		}
	}
	return eligibleAdvisors;
}
复制代码
  1. 遍历candidateAdvisors,如果advisor对象实现了IntroductionAdvisor(Introduction已经很少用了,这里不作讲解).执行canApply判断是否需要加入eligibleAdvisors.
  2. 调用canApply来判断当前advisor的pointcut表达式是否匹配当前class.
  • org.springframework.aop.support.AopUtils#canApply
public static boolean canApply(Advisor advisor, Class<?> targetClass, boolean hasIntroductions) {
	// 当前advisor是否实现IntroductionAdvisor
	if (advisor instanceof IntroductionAdvisor) {
		return ((IntroductionAdvisor) advisor).getClassFilter().matches(targetClass);
	}
	// 判断是否为PointcutAdvisor
	else if (advisor instanceof PointcutAdvisor) {
		// 强转为PointcutAdvisor
		// Spring创建的advisor实例为InstantiationModelAwarePointcutAdvisorImpl,实现了PointcutAdvisor接口
		PointcutAdvisor pca = (PointcutAdvisor) advisor;
		return canApply(pca.getPointcut(), targetClass, hasIntroductions);
	}
	else {
		// It doesn't have a pointcut so we assume it applies.
		// 如果advisor没有pointcut表达式,那么匹配所有的bean
		return true;
	}
}
复制代码
  1. 如果advisor是一个IntroductionAdvisor类型的实例,那么使用ClassFilter进行matches.
  2. 通常我们的advisor都是InstantiationModelAwarePointcutAdvisorImpl实例,所以会执行重载的方法canApply.
  3. 如果当前advisor没有pointcut表达式,那么匹配所有的bean.
  • org.springframework.aop.support.AopUtils#canApply
public static boolean canApply(Pointcut pc, Class<?> targetClass, boolean hasIntroductions) {
	Assert.notNull(pc, "Pointcut must not be null");
	// 如果ClassFilter不匹配,也就是初步筛选失败,直接返回
	if (!pc.getClassFilter().matches(targetClass)) {
		return false;
	}
	// 如果类级别匹配,那么再继续匹配方法是否符合切点表达式
	// 如果当前advisor所指代的方法切点表达式对任意方法都放行,则直接返回
	MethodMatcher methodMatcher = pc.getMethodMatcher();
	if (methodMatcher == MethodMatcher.TRUE) {
		// No need to iterate the methods if we're matching any method anyway...
		return true;
	}
	// 这里将methodMatcher强转为IntroductionAwareMethodMatcher类型
	// 如果目标类不包含Introduction类型的advisor,那么使用
	// IntroductionAwareMethodMatcher.matches方法进行匹配判断可以提升匹配的效率
	// 该方法会判断目标Bean中没有使用Introduction织入新的方法,则可以使用该方法进行静态匹配,从而提升效率
	// 因为Introduction类型的Advisor可以往目标类中织入新的方法,新的方法也可能是被AOP环绕的方法
	IntroductionAwareMethodMatcher introductionAwareMethodMatcher = null;
	if (methodMatcher instanceof IntroductionAwareMethodMatcher) {
		introductionAwareMethodMatcher = (IntroductionAwareMethodMatcher) methodMatcher;
	}

	Set<Class<?>> classes = new LinkedHashSet<>();
	// 判断当前class是不是代理的class对象
	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;
}
复制代码

这里就是构建拦截链中最关键的部分了,Spring要筛选出当前Bean匹配的advisor,借助了AspectJ的能力,也就是AspectJExpressionPointcut封装的AspectJ能力.它支持类级别的匹配,也支持方法级别的匹配,还可以匹配返回值、参数类型等等.
那么顾名思义:

  1. ClassFilter用来匹配Class.
  2. MethodMatcher用来匹配Method.

再来看看整个方法,整体可以看到,先调用了ClassFilter匹配当前Bean是否符合Advisor的切点表达式,再调用了methodMatcher来匹配当前Bean的所有方法是否存在符合advisor切点表达式的.
有兴趣的可以了解一下:
org.aspectj.weaver.tools.PointcutExpression#couldMatchJoinPointsInType.
org.aspectj.weaver.tools.ShadowMatch.

  • 解析后得到的advisor数组

specificInterceptors

总结

  1. Spring AOP的织入是发生在doCreateBean期间的,在其执行初始化时进行织入横切逻辑.但是发生循环依赖时,这个过程会被提前,也就是在暴露引用的时候可能会发生代理的创建.
  2. 在解析到了所有advisors之后,Spring借助AspectJ对bean进行了进一步的筛选,进而筛选到更加精确的advisor,这也使得Spring AOP支持更多元的切入点.
© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享