Spring读源码系列之AOP--07---aop自动代理创建器(拿下AOP的最后一击)

x33g5p2x  于2022-04-26 转载在 Spring  
字(56.4k)|赞(0)|评价(0)|浏览(306)

引子

本系列列举的源码中,很多类没有展开讲,是因为之前的系列文章一直在对aop基础组件进行介绍,因此一定要按照顺序看本系列,否则观看本篇文章的时候,越往后看,越发觉得本文模糊不清,只会粘贴源码,实则不然,因为很多类前文已经讲过,如果本文再展开讲解,那么将无法突出重点

自动代理创建器是spring的aop体系中最重要的一环,也正是因为有他的存在,才让我们使用aop那么方便

先来看看自动代理创建器相关类藏在了哪里:

可以看出来,所有的创建器都是AbstractAutoProxyCreator该抽象类的子类~

当系统比较复杂,或者中需要进行aop进行织入的bean较多时,简单采用ProxyFacotryBean无疑会增加很多工作量(因为每个Bean都得手动写一个)。另外由于要从ProxyFactoryBean获得代理对象,也会使应用和Spring之间的耦合度增加,并且很多时候可维护性不强(我个人认为耦合这个不是最主要的原因,毕竟现在Spring已成为实际上的规范了)。

Spring中自动创建代理器(分类)

在内部,Spring使用BeanPostProcessor让自动生成代理。基于BeanPostProcessor的自动代理创建器的实现类,将根据一些规则在容器实例化Bean时为匹配的Bean生成代理实例。代理创建器可以分为三类:

  • 基于Bean配置名规则的自动代理生成器:允许为一组特定配置名的Bean自动创建代理实例的代理创建器,实现类为BeanNameAutoProxyCreator
  • 基于Advisor匹配机制的自动代理创建器它会对容器中的所有Advisor进行扫描,自动将这些切面应用到匹配的Bean中,实现类是DefaultAdvisorAutoProxyCreator(它也支持前缀匹配)
  • 基于Bean中AspectJ注解的自动代理生成器:为包含AspectJ注解的切入的Bean自动创建代理实例

前提

首先,单独看AbstractAutoProxyCreator的继承体系,分析可知,我们需要先去了解一下ProxyProcessorSupport干了啥(之前系列文章讲过,这里再重复一次),和SmartInstantiationAwareBeanPostProcessor中相关回调接口的调用时机

在AbstractAutoProxyCreator类中,有这样一个属性,并且该属性很多地方用到了,因此这里还需求先科普一下TargetSourceCreator的作用,但是科普这个之前,我们还需要再来聊聊TargetSource

ProxyProcessorSupport

简单的说它就是提供为代理创建器提供了一些公共方法实现:

具有代理处理器通用功能的基类,特别是 ClassLoader 管理和 evaluateProxyInterfaces 算法。

@SuppressWarnings("serial")
public class ProxyProcessorSupport extends ProxyConfig implements Ordered, BeanClassLoaderAware, AopInfrastructureBean {

	/**
AOP的自动代理创建器必须在所有的别的processors之后执行,以确保它可以代理到所有的小伙伴们,即使需要双重代理得那种
	 */
	private int order = Ordered.LOWEST_PRECEDENCE;
    
    //代理类的类加载器
	@Nullable
	private ClassLoader proxyClassLoader = ClassUtils.getDefaultClassLoader();
    
    //代理类的类加载器是否被手动配置了---即用户是否手动指定了类加载器
	private boolean classLoaderConfigured = false;

	public void setOrder(int order) {
		this.order = order;
	}

	@Override
	public int getOrder() {
		return this.order;
	}

	/**
手动设置代理类加载器
	 */
	public void setProxyClassLoader(@Nullable ClassLoader classLoader) {
		this.proxyClassLoader = classLoader;
		//如果不为空,说明手动设置生效,打个标记
		this.classLoaderConfigured = (classLoader != null);
	}
	
	@Nullable
	protected ClassLoader getProxyClassLoader() {
		return this.proxyClassLoader;
	}
//因为继承了BeanClassLoaderAware,因此默认的代理类加载器就是beanFactory用来加载所有bean的beanClassLoader
	@Override
	public void setBeanClassLoader(ClassLoader classLoader) {
	//手动配置的优先级更高,无法覆盖
		if (!this.classLoaderConfigured) {
			this.proxyClassLoader = classLoader;
		}
	}

	/**
	 * 检查给定类上的所有接口,然后检查分析决定代理方式
	 */
	protected void evaluateProxyInterfaces(Class<?> beanClass, ProxyFactory proxyFactory) {
	//拿到目标类上的所有接口
		Class<?>[] targetInterfaces = ClassUtils.getAllInterfacesForClass(beanClass, getProxyClassLoader());
		//是否存在合理的接口---可以决定是否采用jdk动态代理,如果为false则走cglib动态代理
		boolean hasReasonableProxyInterface = false;
		for (Class<?> ifc : targetInterfaces) {
			if (
              //pass内部的回调接口
              !isConfigurationCallbackInterface(ifc) && 
               //pass内部语言接口
               !isInternalLanguageInterface(ifc) &&
					//当前接口内是否存在方法
					ifc.getMethods().length > 0) {
				hasReasonableProxyInterface = true;
				break;
			}
		}
		//如果存在合理的接口
		if (hasReasonableProxyInterface) {
			// Must allow for introductions; can't just set interfaces to the target's interfaces only.
			// 这里Spring的Doc特别强调了:不能值只把合理的接口设置进去,而是都得加入进去
			for (Class<?> ifc : targetInterfaces) {
			//存在合理的接口,说明当前会采用jdk代理,并且代理类需要实现目标对象实现的所有接口
				proxyFactory.addInterface(ifc);
			}
		}
		else {
		// 这个很明显设置true,表示使用CGLIB得方式去创建代理了~~~~
		//proxyFactory继承了proxyConfig,这里调用的是proxyConfig的setProxyTargetClass方法
			proxyFactory.setProxyTargetClass(true);
		}
	}

	/**
判断此接口类型是否属于:容器去回调的类型,这里例举处理一些接口 初始化、销毁、自动刷新、自动关闭、Aware感知等等
	 */
	protected boolean isConfigurationCallbackInterface(Class<?> ifc) {
		return (InitializingBean.class == ifc || DisposableBean.class == ifc || Closeable.class == ifc ||
				AutoCloseable.class == ifc || ObjectUtils.containsElement(ifc.getInterfaces(), Aware.class));
	}

	/**
	是否是如下通用的接口。若实现的是这些接口也会排除,不认为它是实现了接口的类
	 */
	protected boolean isInternalLanguageInterface(Class<?> ifc) {
		return (ifc.getName().equals("groovy.lang.GroovyObject") ||
				ifc.getName().endsWith(".cglib.proxy.Factory") ||
				ifc.getName().endsWith(".bytebuddy.MockAccess"));
	}

}

该类最重要的就是evaluateProxyInterfaces方法,来评估是该采用jdk还是cglib动态代理,该方法决定采用哪种代理方式后,会直接设置ProxyFactory的相关属性

SmartInstantiationAwareBeanPostProcessor

AbstractAutoProxyCreator是对自动代理创建器的一个抽象实现。最重要的是,它实现了SmartInstantiationAwareBeanPostProcessor接口,因此会介入到Spring IoC容器Bean实例化的过程,因此由此为入口进行展开~

Initialization是初始化的意思,意味着该bean后置处理器接口中的两个方法会在bean的初始化前后被调用,这里初始化指的是bean的初始化方法被调用的前后,例如:init-method等

爷爷BeanPostProcessor

public interface BeanPostProcessor {
	@Nullable
	default Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
		return bean;
	}

	@Nullable
	default Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
		return bean;
	}

}

该后置处理器中的两个方法被调用的源码时机如下:

AbstractAutowireCapableBeanFactory

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 {
			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;
	}

initializeBean会在doCreateBean方法中被调用,我保留了该方法主要骨干,大家可以回顾一下,如果想要了解完整流程,可以去看我之前写的初始化流程源码分析:

AbstractAutowireCapableBeanFactory

protected Object doCreateBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
			throws BeanCreationException {
...
			instanceWrapper = createBeanInstance(beanName, mbd, args);
...

			applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
...

		// Eagerly cache singletons to be able to resolve circular references
		// even when triggered by lifecycle interfaces like BeanFactoryAware.
		boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences &&
				isSingletonCurrentlyInCreation(beanName));
				
		if (earlySingletonExposure) {
			addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
			}

		// Initialize the bean instance.
		    Object exposedObject = bean;
			populateBean(beanName, mbd, instanceWrapper);
			exposedObject = initializeBean(beanName, exposedObject, mbd);
 ...
		// Register bean as disposable.
			registerDisposableBeanIfNecessary(beanName, bean, mbd);
..
		return exposedObject;
	}

爸爸InstantiationAwareBeanPostProcessor

Instantiation是实例化的意思,意味着该bean后置处理器相关方法会在bean的实例化前后被调用,这里实例化的意思是bean被创建出来的前后,也就是反射创建实例的前后,注意和上面的初始化过程进行区分

public interface InstantiationAwareBeanPostProcessor extends BeanPostProcessor {
	@Nullable
	default Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) throws BeansException {
		return null;
	}
   
	default boolean postProcessAfterInstantiation(Object bean, String beanName) throws BeansException {
		return true;
	}

	@Nullable
	default PropertyValues postProcessProperties(PropertyValues pvs, Object bean, String beanName)
			throws BeansException {

		return null;
	}

	@Deprecated
	@Nullable
	default PropertyValues postProcessPropertyValues(
			PropertyValues pvs, PropertyDescriptor[] pds, Object bean, String beanName) throws BeansException {

		return pvs;
	}

}

可以看出该后置处理器在爷爷上面增加了四个回调接口,这四个回调接口又可以细分为实例化前后和属性处理接口,那么我们先分析实例化接口何时被调用

AbstractAutowireCapableBeanFactory

doGetBean中,如果缓存没有的话,会按照bean的scope来获取bean,但是无论是啥子scope,最终都是通过createBean来创建bean实例然后返回的

同上,这里只列出重要的部分,其余全部删除,完整版,可以参考之前我写的初始化源码流程分析。

protected Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
			throws BeanCreationException {
			...
		RootBeanDefinition mbdToUse = mbd;
		...
			// Give BeanPostProcessors a chance to return a proxy instead of the target bean instance.
			//这里如果返回的bean不为空,会直接返回,形成短路
			//后面初始化啥子流程,压根不走,因此我们可以在这里通过bean定义创建,然后返回代理对象
			Object bean = resolveBeforeInstantiation(beanName, mbdToUse);
			if (bean != null) {
				return bean;
			}
          ...

		//反射创建bean实例
			Object beanInstance = doCreateBean(beanName, mbdToUse, args);
			...
			return beanInstance;
...
}

大家是不是很奇怪,postProcessAfterInstantiation方法怎么没在doCreateBean方法下面出现呢?

那是因为他放到了populateBean方法里面,并且剩余的两个关于属性的回调接口,也是在这里被调用的,下面我们就一并分析一波:

protected Object doCreateBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
			throws BeanCreationException {
...
		// Initialize the bean instance.
		    Object exposedObject = bean;
		    //populateBean是我们需要重点看的
			populateBean(beanName, mbd, instanceWrapper);
			exposedObject = initializeBean(beanName, exposedObject, mbd);
 ...
	}

正式分析:

postProcessAfterInstantiation返回值是boolean,这点注意一下

protected void populateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw) {
		...
		// Give any InstantiationAwareBeanPostProcessors the opportunity to modify the
		// state of the bean before properties are set. This can be used, for example,
		// to support styles of field injection.
		if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
			for (InstantiationAwareBeanPostProcessor bp : getBeanPostProcessorCache().instantiationAware) {
			//postProcessAfterInstantiation的返回值,觉得是否跳过对当前bean的属性赋值过程,如果返回false,表示跳过
				if (!bp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {
					return;
				}
			}
		}

		PropertyValues pvs = (mbd.hasPropertyValues() ? mbd.getPropertyValues() : null);
        ....
           
		boolean hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors();
		boolean needsDepCheck = (mbd.getDependencyCheck() != AbstractBeanDefinition.DEPENDENCY_CHECK_NONE);

		PropertyDescriptor[] filteredPds = null;
		if (hasInstAwareBpps) {
			if (pvs == null) {
				pvs = mbd.getPropertyValues();
			}
			for (InstantiationAwareBeanPostProcessor bp : getBeanPostProcessorCache().instantiationAware) {
			//postProcessProperties
				PropertyValues pvsToUse = bp.postProcessProperties(pvs, bw.getWrappedInstance(), beanName);
				if (pvsToUse == null) {
					if (filteredPds == null) {
					//filterPropertyDescriptorsForDependencyCheck就是返回当前beanWrapper里面PropertyValues对应的属性描述符集合,只做了一件事,就是会将那些被排除掉,不需要注入的接口,例如:aware接口等,从描述符集合中移除,然后返回
						filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
					}
					//postProcessPropertyValues
					pvsToUse = bp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName);
					if (pvsToUse == null) {
						return;
					}
				}
				pvs = pvsToUse;
			}
		}
...
		if (pvs != null) {
		//属性正式赋值操作
			applyPropertyValues(beanName, mbd, bw, pvs);
		}
	}

还有fresh方法中的preareFactory中也设置了一些依赖忽略的属性,就是如果你在你的类中某处需要注入这些被忽略的接口,那么spring是不会帮你进行自动注入的

儿子SmartInstantiationAwareBeanPostProcessor

public interface SmartInstantiationAwareBeanPostProcessor extends InstantiationAwareBeanPostProcessor {
//预测最终从该处理器的 postProcessBeforeInstantiation 回调返回的 bean 的类型。
//因为上面讲过,如果postProcessBeforeInstantiation返回值非null的话,那么就直接短路了
	@Nullable
	default Class<?> predictBeanType(Class<?> beanClass, String beanName) throws BeansException {
		return null;
	}

//确定用于给定 bean 的候选构造函数。
//createBeanInstance方法内部会尝试通过后置处理器来决定给定bean的构造函数
	@Nullable
	default Constructor<?>[] determineCandidateConstructors(Class<?> beanClass, String beanName)
			throws BeansException {

		return null;
	}

//获取对指定 bean 的早期访问的引用,通常用于解析循环引用。
//
	default Object getEarlyBeanReference(Object bean, String beanName) throws BeansException {
		return bean;
	}

}

determineCandidateConstructors调用时机:

protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) {
....
		// Candidate constructors for autowiring?
		//determineConstructorsFromBeanPostProcessors方法内部会调用determineCandidateConstructors方法
		Constructor<?>[] ctors = determineConstructorsFromBeanPostProcessors(beanClass, beanName);
...
	}

getEarlyBeanReference方法调用时机:

protected Object doCreateBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
			throws BeanCreationException {
...
		// Eagerly cache singletons to be able to resolve circular references
		// even when triggered by lifecycle interfaces like BeanFactoryAware.
		boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences &&
				isSingletonCurrentlyInCreation(beanName));
		if (earlySingletonExposure) {
			if (logger.isTraceEnabled()) {
				logger.trace("Eagerly caching bean '" + beanName +
						"' to allow for resolving potential circular references");
			}
			//为了让提前暴露的bean也可以返回被代理后的对象
			addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
		}
		...

TargetSource

TargetSource是目标对象的一个容器,代理对象每个被拦截的方法调用前,都需要先从TargetSource中获取到目标对象,这样,我们就可以控制每次方法调用作用到的具体对象实例:

JdkDynamicAopProxy的invoke方法:

@Override
	@Nullable
	public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
             ...
             //从targetSource中获取到目标对象
             TargetSource targetSource = this.advised.targetSource;
			target = targetSource.getTarget();
			Class<?> targetClass = (target != null ? target.getClass() : null);
            
            //构建拦截器链
			List<Object> chain = this.advised.getInterceptorsAndDynamicInterceptionAdvice(method, targetClass);
           
           //执行拦截器链和目标方法,然后返回结果
			if (chain.isEmpty()) {
				Object[] argsToUse = AopProxyUtils.adaptArgumentsIfNecessary(method, args);
				retVal = AopUtils.invokeJoinpointUsingReflection(target, method, argsToUse);
			}
			else {
	                MethodInvocation invocation =
						new ReflectiveMethodInvocation(proxy, target, method, args, targetClass, chain);
				retVal = invocation.proceed();
			}

...
			return retVal;
		}
...
	}

CglibAopProxy的内部类DynamicAdvisedInterceptor的intercept方法,也是具体的拦截器:

@Override
		@Nullable
		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 {
				  ...  
				  //从TargetSource中获取到目标对象
				// 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);
				List<Object> chain = this.advised.getInterceptorsAndDynamicInterceptionAdvice(method, targetClass);
				Object retVal;
				
				//拦截器链的构造执行,然后返回结果
				if (chain.isEmpty() && Modifier.isPublic(method.getModifiers())) {
					Object[] argsToUse = AopProxyUtils.adaptArgumentsIfNecessary(method, args);
					retVal = methodProxy.invoke(target, argsToUse);
				}
				else {
					// 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;
			}
...

TargetSource的实现类

之前讲过了,这里不多讲,不清楚的看之前的文章:

Spring繁华的AOP王国—第二讲

TargetSourceCreator

实现可以为特定的 bean 创建特殊的目标源,例如池化目标源。

例如,他们可以根据目标类的属性(例如池属性)进行选择。

AbstractAutoProxyCreator 可以支持多个 TargetSourceCreator,它们将按顺序应用。

@FunctionalInterface
public interface TargetSourceCreator {

	/**
为给定的 bean 创建一个特殊的 TargetSource,如果有的话。
	 */
	@Nullable
	TargetSource getTargetSource(Class<?> beanClass, String beanName);

}

TargetSourceCreator 主要是负责为目标对象生成一个对应的TargetSource,目标对象和TargetSource之间可能是1:1或者n:1或者n:n的关系,这由上面讲的不同的TargetSource实现决定

AbstractBeanFactoryBasedTargetSourceCreator

需要创建原型 bean 的多个实例的 TargetSourceCreator 实现的方便超类。

使用内部 BeanFactory 管理目标实例,将原始 bean 定义复制到此内部工厂。

这是必要的,因为原始 BeanFactory 将只包含通过自动代理创建的代理实例。

public abstract class AbstractBeanFactoryBasedTargetSourceCreator
		implements TargetSourceCreator, BeanFactoryAware, DisposableBean {

	protected final Log logger = LogFactory.getLog(getClass());

	private ConfigurableBeanFactory beanFactory;

	/** Internally used DefaultListableBeanFactory instances, keyed by bean name. */
	private final Map<String, DefaultListableBeanFactory> internalBeanFactories =
			new HashMap<>();

	@Override
	public final void setBeanFactory(BeanFactory beanFactory) {
		if (!(beanFactory instanceof ConfigurableBeanFactory)) {
			throw new IllegalStateException("Cannot do auto-TargetSource creation with a BeanFactory " +
					"that doesn't implement ConfigurableBeanFactory: " + beanFactory.getClass());
		}
		this.beanFactory = (ConfigurableBeanFactory) beanFactory;
	}

	/**
	 * Return the BeanFactory that this TargetSourceCreators runs in.
	 */
	protected final BeanFactory getBeanFactory() {
		return this.beanFactory;
	}

	//---------------------------------------------------------------------
	// Implementation of the TargetSourceCreator interface
	//---------------------------------------------------------------------

	@Override
	@Nullable
	public final TargetSource getTargetSource(Class<?> beanClass, String beanName) {
	//createBeanFactoryBasedTargetSource是抽象方法,子类实现,该方法作用是为当前bean创建一个AbstractBeanFactoryBasedTargetSource 
		AbstractBeanFactoryBasedTargetSource targetSource =
				createBeanFactoryBasedTargetSource(beanClass, beanName);
		//如果得到的是null,那么直接返回null		
		if (targetSource == null) {
			return null;
		}

		if (logger.isDebugEnabled()) {
			logger.debug("Configuring AbstractBeanFactoryBasedTargetSource: " + targetSource);
		}
        
        //拿到当前bean关联的内部beanFactory实例
		DefaultListableBeanFactory internalBeanFactory = getInternalBeanFactoryForBean(beanName);

		// We need to override just this bean definition, as it may reference other beans
		// and we're happy to take the parent's definition for those.
		// Always use prototype scope if demanded.
		BeanDefinition bd = this.beanFactory.getMergedBeanDefinition(beanName);
		GenericBeanDefinition bdCopy = new GenericBeanDefinition(bd);
		if (isPrototypeBased()) {
			bdCopy.setScope(BeanDefinition.SCOPE_PROTOTYPE);
		}
		internalBeanFactory.registerBeanDefinition(beanName, bdCopy);

		// Complete configuring the PrototypeTargetSource.
		targetSource.setTargetBeanName(beanName);
		targetSource.setBeanFactory(internalBeanFactory);

		return targetSource;
	}

	/**
	 * Return the internal BeanFactory to be used for the specified bean.
	 */
	protected DefaultListableBeanFactory getInternalBeanFactoryForBean(String beanName) {
		synchronized (this.internalBeanFactories) {
			DefaultListableBeanFactory internalBeanFactory = this.internalBeanFactories.get(beanName);
			if (internalBeanFactory == null) {
				internalBeanFactory = buildInternalBeanFactory(this.beanFactory);
				this.internalBeanFactories.put(beanName, internalBeanFactory);
			}
			return internalBeanFactory;
		}
	}

	/**
	 * Build an internal BeanFactory for resolving target beans.
	 */
	protected DefaultListableBeanFactory buildInternalBeanFactory(ConfigurableBeanFactory containingFactory) {
		// Set parent so that references (up container hierarchies) are correctly resolved.
		DefaultListableBeanFactory internalBeanFactory = new DefaultListableBeanFactory(containingFactory);

		// Required so that all BeanPostProcessors, Scopes, etc become available.
		internalBeanFactory.copyConfigurationFrom(containingFactory);

		// Filter out BeanPostProcessors that are part of the AOP infrastructure,
		// since those are only meant to apply to beans defined in the original factory.
		internalBeanFactory.getBeanPostProcessors().removeIf(beanPostProcessor ->
				beanPostProcessor instanceof AopInfrastructureBean);

		return internalBeanFactory;
	}

	/**
	 * Destroys the internal BeanFactory on shutdown of the TargetSourceCreator.
	 * @see #getInternalBeanFactoryForBean
	 */
	@Override
	public void destroy() {
		synchronized (this.internalBeanFactories) {
			for (DefaultListableBeanFactory bf : this.internalBeanFactories.values()) {
				bf.destroySingletons();
			}
		}
	}

	//---------------------------------------------------------------------
	// Template methods to be implemented by subclasses
	//---------------------------------------------------------------------

	/**
返回此 TargetSourceCreator 是否是prototype。目标 bean 定义的范围将相应设置。
	 */
	protected boolean isPrototypeBased() {
		return true;
	}

	/**
如果子类希望为此 bean 创建自定义 TargetSource,
则必须实现此方法以返回新的 AbstractPrototypeBasedTargetSource,
如果不感兴趣,则返回 null,在这种情况下,不会创建特殊的目标源。
子类不应在 AbstractPrototypeBasedTargetSource 上调用 setTargetBeanName 
或 setBeanFactory:此类的 getTargetSource() 实现会这样做。
	 */
	@Nullable
	protected abstract AbstractBeanFactoryBasedTargetSource createBeanFactoryBasedTargetSource(
			Class<?> beanClass, String beanName);

}
QuickTargetSourceCreator

Convenient TargetSourceCreator using bean name prefixes to create one of three well-known TargetSource types:

  • : CommonsPool2TargetSource
  • % ThreadLocalTargetSource
  • ! PrototypeTargetSource
public class QuickTargetSourceCreator extends AbstractBeanFactoryBasedTargetSourceCreator {

	/**
	 * The CommonsPool2TargetSource prefix.
	 */
	public static final String PREFIX_COMMONS_POOL = ":";

	/**
	 * The ThreadLocalTargetSource prefix.
	 */
	public static final String PREFIX_THREAD_LOCAL = "%";

	/**
	 * The PrototypeTargetSource prefix.
	 */
	public static final String PREFIX_PROTOTYPE = "!";

	@Override
	@Nullable
	protected final AbstractBeanFactoryBasedTargetSource createBeanFactoryBasedTargetSource(
			Class<?> beanClass, String beanName) {

		if (beanName.startsWith(PREFIX_COMMONS_POOL)) {
			CommonsPool2TargetSource cpts = new CommonsPool2TargetSource();
			cpts.setMaxSize(25);
			return cpts;
		}
		else if (beanName.startsWith(PREFIX_THREAD_LOCAL)) {
			return new ThreadLocalTargetSource();
		}
		else if (beanName.startsWith(PREFIX_PROTOTYPE)) {
			return new PrototypeTargetSource();
		}
		else {
			// No match. Don't create a custom target source.
			return null;
		}
	}

}
LazyInitTargetSourceCreator

TargetSourceCreator 为定义为“lazy-init”的每个 bean 强制执行 LazyInitTargetSource。这将导致为每个 bean 创建一个代理,允许在不实际初始化目标 bean 实例的情况下获取对此类 bean 的引用

注册为自动代理创建者的自定义 TargetSourceCreator,结合特定 bean 的自定义拦截器或仅用于创建惰性初始化代理。例如,作为 XML 应用程序上下文定义中的自动检测基础设施 bean:

<bean class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator">
     <property name="beanNames" value="*" /> <!-- apply to all beans -->
     <property name="customTargetSourceCreators">
       <list>
         <bean class="org.springframework.aop.framework.autoproxy.target.LazyInitTargetSourceCreator" />
       </list>
     </property>
   </bean>
  
   <bean id="myLazyInitBean" class="mypackage.MyBeanClass" lazy-init="true">
     <!-- ... -->
   </bean>

该类源码:

public class LazyInitTargetSourceCreator extends AbstractBeanFactoryBasedTargetSourceCreator {

	@Override
	protected boolean isPrototypeBased() {
		return false;
	}

	@Override
	@Nullable
	protected AbstractBeanFactoryBasedTargetSource createBeanFactoryBasedTargetSource(
			Class<?> beanClass, String beanName) {

		if (getBeanFactory() instanceof ConfigurableListableBeanFactory) {
			BeanDefinition definition =
					((ConfigurableListableBeanFactory) getBeanFactory()).getBeanDefinition(beanName);
			if (definition.isLazyInit()) {
				return new LazyInitTargetSource();
			}
		}
		return null;
	}

}

正文

终于在唠叨完了所有前情提要的情况下,可以进入正题了,下面开始正式讲解自动代理创建器相关知识点:

AbstractAutoProxyCreator—自动代理创建器抽象基类

public abstract class AbstractAutoProxyCreator extends ProxyProcessorSupport
		implements SmartInstantiationAwareBeanPostProcessor, BeanFactoryAware {

	/**
	 * Convenience constant for subclasses: Return value for "do not proxy"
	 * 不进行代理
	 */
	@Nullable
	protected static final Object[] DO_NOT_PROXY = null;

	/**
	 * Convenience constant for subclasses: Return value for
	 * "proxy without additional interceptors, just the common ones".
	 * 使用代理,但是没有额外的拦截器来增强代理类
	 */
	protected static final Object[] PROXY_WITHOUT_ADDITIONAL_INTERCEPTORS = new Object[0];

	/** Logger available to subclasses. */
	protected final Log logger = LogFactory.getLog(getClass());

	/** advisor和advice相关的适配器 */
	private AdvisorAdapterRegistry advisorAdapterRegistry = GlobalAdvisorAdapterRegistry.getInstance();

	/**
	 * Indicates whether or not the proxy should be frozen. Overridden from super
	 * to prevent the configuration from becoming frozen too early.
	 */
	private boolean freezeProxy = false;

	/** Default is no common interceptors. */
	private String[] interceptorNames = new String[0];

	private boolean applyCommonInterceptorsFirst = true;

//这是一个数组,说明可以同时设置多个TargetSourceCreator
	@Nullable
	private TargetSourceCreator[] customTargetSourceCreators;

//因为当前类实现了BeanFactoryAware ,因此使用该变量可以保存传入的IOC容器引用
	@Nullable
	private BeanFactory beanFactory;

//存放被targetSource包裹的beanName集合
	private final Set<String> targetSourcedBeans = Collections.newSetFromMap(new ConcurrentHashMap<>(16));
//存放早期暴露的代理类引用集合---参考SmartInstantiationAwareBeanPostProcessor #getEarlyBeanReference
	private final Map<Object, Object> earlyProxyReferences = new ConcurrentHashMap<>(16);
//缓存生成的代理对象
	private final Map<Object, Class<?>> proxyTypes = new ConcurrentHashMap<>(16);
//该集合里的bean,不需要被代理或者已经被代理过的bean
	private final Map<Object, Boolean> advisedBeans = new ConcurrentHashMap<>(256);

	@Override
	public void setFrozen(boolean frozen) {
		this.freezeProxy = frozen;
	}

	@Override
	public boolean isFrozen() {
		return this.freezeProxy;
	}

	public void setAdvisorAdapterRegistry(AdvisorAdapterRegistry advisorAdapterRegistry) {
		this.advisorAdapterRegistry = advisorAdapterRegistry;
	}

	/**
设置要按此顺序应用的自定义 TargetSourceCreators。
如果列表为空,或者它们都返回 null,则将为每个 bean 创建一个 SingletonTargetSource。

请注意,即使对于没有找到advice或advisor的目标 bean,TargetSourceCreators 也会启动。如果 TargetSourceCreator 返回特定 bean 的 TargetSource,则无论如何都会代理该 bean。

仅当在 BeanFactory 中使用此后处理器并触发其 BeanFactoryAware 回调时,才能调用 TargetSourceCreators。
	 */
	public void setCustomTargetSourceCreators(TargetSourceCreator... targetSourceCreators) {
		this.customTargetSourceCreators = targetSourceCreators;
	}

	/**
设置常用拦截器。这些必须是当前工厂中的 bean 名称。它们可以是 Spring 支持的任何advice或advisor类型。

如果未设置此属性,则公共拦截器将为零。如果我们只需要“特定”拦截器(例如匹配advisors),这是完全有效的。
	 */
	public void setInterceptorNames(String... interceptorNames) {
		this.interceptorNames = interceptorNames;
	}

//每个bean都有自己特定的拦截器链,但是如果设置了公共拦截器链,那么该公共拦截器链将会应用到所有被代理的bean上

	/**
设置是否应在特定于 bean 的拦截器之前应用公共拦截器。默认为“真”;否则,将首先应用特定于 bean 的拦截器。
	 */
	public void setApplyCommonInterceptorsFirst(boolean applyCommonInterceptorsFirst) {
		this.applyCommonInterceptorsFirst = applyCommonInterceptorsFirst;
	}

	@Override
	public void setBeanFactory(BeanFactory beanFactory) {
		this.beanFactory = beanFactory;
	}

	@Nullable
	protected BeanFactory getBeanFactory() {
		return this.beanFactory;
	}

//这里返回的应该是代理对象的类型
	@Override
	@Nullable
	public Class<?> predictBeanType(Class<?> beanClass, String beanName) {
		if (this.proxyTypes.isEmpty()) {
			return null;
		}
		Object cacheKey = getCacheKey(beanClass, beanName);
		return this.proxyTypes.get(cacheKey);
	}

	@Override
	@Nullable
	public Constructor<?>[] determineCandidateConstructors(Class<?> beanClass, String beanName) {
		return null;
	}

//earlyProxyReferences集合在这里被使用,主要是记录被提前暴露的bean
	@Override
	public Object getEarlyBeanReference(Object bean, String beanName) {
		Object cacheKey = getCacheKey(bean.getClass(), beanName);
		this.earlyProxyReferences.put(cacheKey, bean);
		//会尝试去代理bean,如果不需要代理,就直接返回bean
		return wrapIfNecessary(bean, beanName, cacheKey);
	}

//InstantiationAwareBeanPostProcessor接口中的回调接口
//会尝试去代理传入的bean,如果代理成功,返回代理对象,形成短路
	@Override
	public Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) {
		Object cacheKey = getCacheKey(beanClass, beanName);

		if (!StringUtils.hasLength(beanName) || !this.targetSourcedBeans.contains(beanName)) {
			if (this.advisedBeans.containsKey(cacheKey)) {
				return null;
			}
			if (isInfrastructureClass(beanClass) || shouldSkip(beanClass, beanName)) {
				this.advisedBeans.put(cacheKey, Boolean.FALSE);
				return null;
			}
		}

		// Create proxy here if we have a custom TargetSource.
		// Suppresses unnecessary default instantiation of the target bean:
		// The TargetSource will handle target instances in a custom fashion.
		//如何容器中存在该beanName,并且TargetSourceCreators不为空,那么会使用TargetSourceCreator创建TargetSource后返回
		//否则返回null
		TargetSource targetSource = getCustomTargetSource(beanClass, beanName);
		//需要进行代理
		if (targetSource != null) {
			if (StringUtils.hasLength(beanName)) {
				this.targetSourcedBeans.add(beanName);
			}
			//获取到当前bean的拦截器链
			Object[] specificInterceptors = getAdvicesAndAdvisorsForBean(beanClass, beanName, targetSource);
			//创建代理对象
			Object proxy = createProxy(beanClass, beanName, specificInterceptors, targetSource);
			//缓存起来
			this.proxyTypes.put(cacheKey, proxy.getClass());
			//返回代理对象,形成短路
			return proxy;
		}
       //targetSource 为null,说明不需要进行代理操作,直接返回null,不进行短路处理
		return null;
	}

	@Override
	public PropertyValues postProcessProperties(PropertyValues pvs, Object bean, String beanName) {
		return pvs;  // skip postProcessPropertyValues
	}

	/**
BeanPostProcessor中的回调接口,bean初始后被调用
	 */
	@Override
	public Object postProcessAfterInitialization(@Nullable Object bean, String beanName) {
		if (bean != null) {
			Object cacheKey = getCacheKey(bean.getClass(), beanName);
			//earlyProxyReferences集合中如果已经有过了该bean,就不需要再尝试代理了
			//因为earlyProxyReferences集合中的bean,在被暴露出去之前,都已经尝试过进行代理操作了
			if (this.earlyProxyReferences.remove(cacheKey) != bean) {
				return wrapIfNecessary(bean, beanName, cacheKey);
			}
		}
		return bean;
	}

	protected Object getCacheKey(Class<?> beanClass, @Nullable String beanName) {
		if (StringUtils.hasLength(beanName)) {
			return (FactoryBean.class.isAssignableFrom(beanClass) ?
					BeanFactory.FACTORY_BEAN_PREFIX + beanName : beanName);
		}
		else {
			return beanClass;
		}
	}

	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.
		//获取拦截器
		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 boolean isInfrastructureClass(Class<?> beanClass) {
		boolean retVal = Advice.class.isAssignableFrom(beanClass) ||
				Pointcut.class.isAssignableFrom(beanClass) ||
				Advisor.class.isAssignableFrom(beanClass) ||
				AopInfrastructureBean.class.isAssignableFrom(beanClass);
		if (retVal && logger.isTraceEnabled()) {
			logger.trace("Did not attempt to auto-proxy infrastructure class [" + beanClass.getName() + "]");
		}
		return retVal;
	}

//OriginalInstance不需要进行代理,感兴趣可以了解一下
	protected boolean shouldSkip(Class<?> beanClass, String beanName) {
		return AutoProxyUtils.isOriginalInstance(beanName, beanClass);
	}

	@Nullable
	protected TargetSource getCustomTargetSource(Class<?> beanClass, String beanName) {
		// We can't create fancy target sources for directly registered singletons.
		if (this.customTargetSourceCreators != null &&
				this.beanFactory != null && this.beanFactory.containsBean(beanName)) {
			for (TargetSourceCreator tsc : this.customTargetSourceCreators) {
			//如果有一个TargetSourceCreator的getTargetSource返回值不为空,那么直接返回其创建的TargetSource 
				TargetSource ts = tsc.getTargetSource(beanClass, beanName);
				if (ts != null) {
					// Found a matching TargetSource.
					if (logger.isTraceEnabled()) {
						logger.trace("TargetSourceCreator [" + tsc +
								"] found custom TargetSource for bean with name '" + beanName + "'");
					}
					return ts;
				}
			}
		}

		// No custom TargetSource found.
		return null;
	}

//创建代理对象
	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 proxyFactory = new ProxyFactory();
		//这里copy的是ProxyConfig的配置,两者都继承了该类
		proxyFactory.copyFrom(this);

       //isProxyTargetClass为true,说明要用cglib代理
		if (proxyFactory.isProxyTargetClass()) {
			// Explicit handling of JDK proxy targets (for introduction advice scenarios)
			//如果当前bean是jdk的代理类
			if (Proxy.isProxyClass(beanClass)) {
				// Must allow for introductions; can't just set interfaces to the proxy's interfaces only.
				for (Class<?> ifc : beanClass.getInterfaces()) {
					//拿到jdk代理类继承的所有接口,添加进当前proxyFactory
					proxyFactory.addInterface(ifc);
				}
			}
		}
		else {
			// No proxyTargetClass flag enforced, let's apply our default checks...
			//shouldProxyTargetClass返回值取决于:Boolean.TRUE.equals(bd.getAttribute(PRESERVE_TARGET_CLASS_ATTRIBUTE));
			//即当前bean定义中的PRESERVE_TARGET_CLASS_ATTRIBUTE是否存在,并且对应的值是否为true,如果为true,则采用cglib进行代理
			if (shouldProxyTargetClass(beanClass, beanName)) {
				proxyFactory.setProxyTargetClass(true);
			}
			else {
			//进行常规判断,该方法属于父类ProxyProcessorSupport--上面分析过了
				evaluateProxyInterfaces(beanClass, proxyFactory);
			}
		}
       //拦截器和targetSource设置进proxyFactory
		Advisor[] advisors = buildAdvisors(beanName, specificInterceptors);
		proxyFactory.addAdvisors(advisors);
		proxyFactory.setTargetSource(targetSource);
		//空实现,子类可以进行定制操作
		customizeProxyFactory(proxyFactory);

		proxyFactory.setFrozen(this.freezeProxy);
		if (advisorsPreFiltered()) {
			proxyFactory.setPreFiltered(true);
		}

		// Use original ClassLoader if bean class not locally loaded in overriding class loader
		ClassLoader classLoader = getProxyClassLoader();
		if (classLoader instanceof SmartClassLoader && classLoader != beanClass.getClassLoader()) {
			classLoader = ((SmartClassLoader) classLoader).getOriginalClassLoader();
		}
		//创建代理对象
		return proxyFactory.getProxy(classLoader);
	}

//是否使用cglib代理
	protected boolean shouldProxyTargetClass(Class<?> beanClass, @Nullable String beanName) {
		return (this.beanFactory instanceof ConfigurableListableBeanFactory &&
				AutoProxyUtils.shouldProxyTargetClass((ConfigurableListableBeanFactory) this.beanFactory, beanName));
	}

	/**
	 * Return whether the Advisors returned by the subclass are pre-filtered
	 * to match the bean's target class already, allowing the ClassFilter check
	 * to be skipped when building advisors chains for AOP invocations.
	 *  Subclasses may override this if they
	 * will always return pre-filtered Advisors.
	 */
	protected boolean advisorsPreFiltered() {
		return false;
	}

	/**
	 * Determine the advisors for the given bean, including the specific interceptors
	 * as well as the common interceptor, all adapted to the Advisor interface.
	 */
	protected Advisor[] buildAdvisors(@Nullable String beanName, @Nullable Object[] specificInterceptors) {
		// Handle prototypes correctly...
		//这里解析的是用户设置的commonInterceptors的beanNames数组,默认为空
		//resolveInterceptorNames就是拿着beanName去IOC容器中找出对应的bean,再通过适配器转换为统一的advisor后返回
		Advisor[] commonInterceptors = resolveInterceptorNames();
       
		List<Object> allInterceptors = new ArrayList<>();
		if (specificInterceptors != null) {
			if (specificInterceptors.length > 0) {
				// specificInterceptors may equal PROXY_WITHOUT_ADDITIONAL_INTERCEPTORS
				allInterceptors.addAll(Arrays.asList(specificInterceptors));
			}
			if (commonInterceptors.length > 0) {
				if (this.applyCommonInterceptorsFirst) {
					allInterceptors.addAll(0, Arrays.asList(commonInterceptors));
				}
				else {
					allInterceptors.addAll(Arrays.asList(commonInterceptors));
				}
			}
		}
		if (logger.isTraceEnabled()) {
			int nrOfCommonInterceptors = commonInterceptors.length;
			int nrOfSpecificInterceptors = (specificInterceptors != null ? specificInterceptors.length : 0);
			logger.trace("Creating implicit proxy for bean '" + beanName + "' with " + nrOfCommonInterceptors +
					" common interceptors and " + nrOfSpecificInterceptors + " specific interceptors");
		}

		Advisor[] advisors = new Advisor[allInterceptors.size()];
		for (int i = 0; i < allInterceptors.size(); i++) {
			advisors[i] = this.advisorAdapterRegistry.wrap(allInterceptors.get(i));
		}
		return advisors;
	}

	/**
	 * Resolves the specified interceptor names to Advisor objects.
	 * @see #setInterceptorNames
	 */
	private Advisor[] resolveInterceptorNames() {
		BeanFactory bf = this.beanFactory;
		ConfigurableBeanFactory cbf = (bf instanceof ConfigurableBeanFactory ? (ConfigurableBeanFactory) bf : null);
		List<Advisor> advisors = new ArrayList<>();
		for (String beanName : this.interceptorNames) {
			if (cbf == null || !cbf.isCurrentlyInCreation(beanName)) {
				Assert.state(bf != null, "BeanFactory required for resolving interceptor names");
				Object next = bf.getBean(beanName);
				advisors.add(this.advisorAdapterRegistry.wrap(next));
			}
		}
		return advisors.toArray(new Advisor[0]);
	}

	/**
	 * Subclasses may choose to implement this: for example,
	 * to change the interfaces exposed.
	 * <p>The default implementation is empty.
	 * @param proxyFactory a ProxyFactory that is already configured with
	 * TargetSource and interfaces and will be used to create the proxy
	 * immediately after this method returns
	 */
	protected void customizeProxyFactory(ProxyFactory proxyFactory) {
	}

	/**
当前bean是否要被代理,如果需要被代理,返回他相关的增强器集合,该方法有子类实现
	 */
	@Nullable
	protected abstract Object[] getAdvicesAndAdvisorsForBean(Class<?> beanClass, String beanName,
			@Nullable TargetSource customTargetSource) throws BeansException;

}

AbstractAutoProxyCreator的创建步骤就是上面源码分析的,它就相当于一个代理创建的模版,规定了一些步骤。获取Advisor的getAdvicesAndAdvisorsForBean由各子类自己去实现~~~

接下来主要是根据对方法getAdvicesAndAdvisorsForBean()的实现不一样,策略也就有两种了。它有两个直接实现:BeanNameAutoProxyCreator和AbstractAdvisorAutoProxyCreator。

BeanNameAutoProxyCreator—按照规定的beanName数组,对bean实施代理

顾名思义,它和Advisor无关,只和BeanName有关(只有名字匹配上了,都会给创建一个代理类)

所以我认为它是个半自动的,哪些需要创建代理,还需要我们自己指定(虽然支持*通配符)

public class BeanNameAutoProxyCreator extends AbstractAutoProxyCreator {

	private static final String[] NO_ALIASES = new String[0];

	@Nullable
	private List<String> beanNames;

	/**
Set the names of the beans that should automatically get wrapped with proxies. 
A name can specify a prefix to match by ending with "*",
 e.g. "myBean,tx*" will match the bean named "myBean" and all beans whose name start with "tx".

NOTE: In case of a FactoryBean, only the objects created by the FactoryBean will get proxied.
 This default behavior applies as of Spring 2.0. 
 If you intend to proxy a FactoryBean instance itself (a rare use case, but Spring 1.2's default behavior),
  specify the bean name of the FactoryBean including the factory-bean prefix "&": e.g. "&myFactoryBean".
	 */
	public void setBeanNames(String... beanNames) {
		Assert.notEmpty(beanNames, "'beanNames' must not be empty");
		this.beanNames = new ArrayList<>(beanNames.length);
		for (String mappedName : beanNames) {
			this.beanNames.add(StringUtils.trimWhitespace(mappedName));
		}
	}

	/**
	 * Delegate to {@link AbstractAutoProxyCreator#getCustomTargetSource(Class, String)}
	 * if the bean name matches one of the names in the configured list of supported
	 * names, returning {@code null} otherwise.
	 * @since 5.3
	 * @see #setBeanNames(String...)
	 */
	@Override
	protected TargetSource getCustomTargetSource(Class<?> beanClass, String beanName) {
		return (isSupportedBeanName(beanClass, beanName) ?
				super.getCustomTargetSource(beanClass, beanName) : null);
	}

	/**
	 * Identify as a bean to proxy if the bean name matches one of the names in
	 * the configured list of supported names.
	 */
	@Override
	@Nullable
	protected Object[] getAdvicesAndAdvisorsForBean(
			Class<?> beanClass, String beanName, @Nullable TargetSource targetSource) {

		return (isSupportedBeanName(beanClass, beanName) ?
				PROXY_WITHOUT_ADDITIONAL_INTERCEPTORS : DO_NOT_PROXY);
	}

	/**
	 * Determine if the bean name for the given bean class matches one of the names
	 * in the configured list of supported names.
	 */
	private boolean isSupportedBeanName(Class<?> beanClass, String beanName) {
		if (this.beanNames != null) {
		//对工厂bean做特殊处理
			boolean isFactoryBean = FactoryBean.class.isAssignableFrom(beanClass);
			for (String mappedName : this.beanNames) {
				if (isFactoryBean) {
					if (!mappedName.startsWith(BeanFactory.FACTORY_BEAN_PREFIX)) {
						continue;
					}
					mappedName = mappedName.substring(BeanFactory.FACTORY_BEAN_PREFIX.length());
				}
				if (isMatch(beanName, mappedName)) {
					return true;
				}
			}
            
            //当前bean的别名数组中有无匹配的 
			BeanFactory beanFactory = getBeanFactory();
			String[] aliases = (beanFactory != null ? beanFactory.getAliases(beanName) : NO_ALIASES);
			for (String alias : aliases) {
				for (String mappedName : this.beanNames) {
					if (isMatch(alias, mappedName)) {
						return true;
					}
				}
			}
		}
		return false;
	}

	/**
	 * Determine if the given bean name matches the mapped name.
	 * The default implementation checks for "xxx*", "*xxx" and "*xxx*" matches,
	 * as well as direct equality. Can be overridden in subclasses.
	 */
	protected boolean isMatch(String beanName, String mappedName) {
		return PatternMatchUtils.simpleMatch(mappedName, beanName);
	}

}
简单使用
@Bean
    public BeanNameAutoProxyCreator beanNameAutoProxyCreator() {
        BeanNameAutoProxyCreator beanNameAutoProxyCreator = new BeanNameAutoProxyCreator();
        // 给所有以serviceImpl结尾的类创建代理对象(支持正则)  备注:aliases也是被支持的
        // 注意此处若只写`*Service` 是匹配不上helloServiceImpl
        beanNameAutoProxyCreator.setBeanNames("*ServiceImpl");

        // 备注:它要想使用拦截,只能通过setInterceptorNames,从容器内拿Advice的实现类(自己书写)
        //下面这样设置的是通用拦截器
        beanNameAutoProxyCreator.setInterceptorNames("myMethodInteceptor");
        return beanNameAutoProxyCreator;
    }

就这样配置,MyMethodInteceptor这个拦截器,它就会作用于拦截所有的*ServiceImpl上。

若我们使用@EnableAspectJAutoProxy启动自动代理的话,Spring自动会给我们注册一个Bean:AnnotationAwareAspectJAutoProxyCreator,它是一个AbstractAdvisorAutoProxyCreator,和AspectJ注解相关~

备注:此时我们采用了BeanNameAutoProxyCreator,自然就不用再@EnableAspectJAutoProxy,自然@Aspect切面也就不生效了。 当然,也可以开启的,这样他俩就联合生效了(但不太建议去这么使用)

需要注意的是:如果一个对象被切多次(比如使用@Async、事务都会创建代理对象),最终这个对象代理可能是对层的:如下所示:

另外,如果你想用自己注册的@Bean代替@EnableAspectJAutoProxy默认给你注册的自动创建器,那么你可以注册一个Bean名称如下的Bean即可:

// 手动注册一个自动代理创建器,且名字务必叫AopConfigUtils.AUTO_PROXY_CREATOR_BEAN_NAME
@Bean(AopConfigUtils.AUTO_PROXY_CREATOR_BEAN_NAME) 
public BeanNameAutoProxyCreator beanNameAutoProxyCreator() {
	...
}
AbstractAdvisorAutoProxyCreator—getAdvicesAndAdvisorsForBean

顾名思义,它和Advisor有关(只有被切入的类,才会给它创建一个代理类),它的核心方法是实现了父类的:
getAdvicesAndAdvisorsForBean来获取Advisor们

子类可以覆盖 findCandidateAdvisors() 方法以返回应用于任何对象的自定义顾问列表。子类还可以覆盖继承的 shouldSkip 方法以从自动代理中排除某些对象。

需要排序的advice或advisor应使用 @Order 注释或实现 org.springframework.core.Ordered 接口。

此类使用 AnnotationAwareOrderComparator 对advisor进行排序。

未使用@Order 注解或未实现 Ordered 接口的 Advisor 将被视为无序;它们将以未定义的顺序出现在advisor链的末尾。

public abstract class AbstractAdvisorAutoProxyCreator extends AbstractAutoProxyCreator {
// 这个类是重点,后面会详细介绍
	@Nullable
	private BeanFactoryAdvisorRetrievalHelper advisorRetrievalHelper;

	@Override
	public void setBeanFactory(BeanFactory beanFactory) {
		super.setBeanFactory(beanFactory);
		if (!(beanFactory instanceof ConfigurableListableBeanFactory)) {
			throw new IllegalArgumentException(
					"AdvisorAutoProxyCreator requires a ConfigurableListableBeanFactory: " + beanFactory);
		}
		//初始化advisorRetrievalHelper
		initBeanFactory((ConfigurableListableBeanFactory) beanFactory);
	}

	protected void initBeanFactory(ConfigurableListableBeanFactory beanFactory) {
		this.advisorRetrievalHelper = new BeanFactoryAdvisorRetrievalHelperAdapter(beanFactory);
	}

//获得当前传入bean关联的增强器链
	@Override
	@Nullable
	protected Object[] getAdvicesAndAdvisorsForBean(
			Class<?> beanClass, String beanName, @Nullable TargetSource targetSource) {
//寻找可用用于当bean上的拦截器
		List<Advisor> advisors = findEligibleAdvisors(beanClass, beanName);
		if (advisors.isEmpty()) {
			return DO_NOT_PROXY;
		}
		return advisors.toArray();
	}

//寻找可用用于当bean上的拦截器
	protected List<Advisor> findEligibleAdvisors(Class<?> beanClass, String beanName) {
	//探测获取到容器中所有增强器
		List<Advisor> candidateAdvisors = findCandidateAdvisors();
	// 对上面找到的候选的Advisors们,进行过滤操作~~~  看看Advisor能否被用在Bean上(根据Advisor的PointCut判断)
		// 主要依赖于AopUtils.findAdvisorsThatCanApply()方法  在工具类讲解中有详细分析的
		// 逻辑简单概述为:看目标类是不是符合代理对象的条件,如果符合就把Advisor加到集合中,最后返回集合
		// 简单的说:它就是会根据ClassFilter和MethodMatcher等等各种匹配。(但凡只有有一个方法被匹配上了,就会给他创建代理类了)
		// 方法用的ReflectionUtils.getAllDeclaredMethods,**因此哪怕是私有方法,匹配上都会给创建的代理对象,这点务必要特别特别的注意**
		List<Advisor> eligibleAdvisors = findAdvisorsThatCanApply(candidateAdvisors, beanClass, beanName);
		//钩子:子类可以覆盖,添加更多的增强器
		extendAdvisors(eligibleAdvisors);
		if (!eligibleAdvisors.isEmpty()) {
		//排序
			eligibleAdvisors = sortAdvisors(eligibleAdvisors);
		}
		return eligibleAdvisors;
	}

	protected List<Advisor> findCandidateAdvisors() {
		Assert.state(this.advisorRetrievalHelper != null, "No BeanFactoryAdvisorRetrievalHelper available");
		return this.advisorRetrievalHelper.findAdvisorBeans();
	}

	protected List<Advisor> findAdvisorsThatCanApply(
			List<Advisor> candidateAdvisors, Class<?> beanClass, String beanName) {

		ProxyCreationContext.setCurrentProxiedBeanName(beanName);
		try {
		//AopUtils.findAdvisorsThatCanApply本系列文章分析过
		//
			return AopUtils.findAdvisorsThatCanApply(candidateAdvisors, beanClass);
		}
		finally {
			ProxyCreationContext.setCurrentProxiedBeanName(null);
		}
	}

	/**
	 * Return whether the Advisor bean with the given name is eligible
	 * for proxying in the first place.
     子类覆盖实现
	 */
	protected boolean isEligibleAdvisorBean(String beanName) {
		return true;
	}

	protected List<Advisor> sortAdvisors(List<Advisor> advisors) {
		AnnotationAwareOrderComparator.sort(advisors);
		return advisors;
	}

	/**
留个子类覆盖的钩子函数,可以往增强器链中添加额外的增强器
	 */
	protected void extendAdvisors(List<Advisor> candidateAdvisors) {
	}

	/**
	 * This auto-proxy creator always returns pre-filtered Advisors.
	 */
	@Override
	protected boolean advisorsPreFiltered() {
		return true;
	}

	/**
	 * Subclass of BeanFactoryAdvisorRetrievalHelper that delegates to
	 * surrounding AbstractAdvisorAutoProxyCreator facilities.
	 */
	private class BeanFactoryAdvisorRetrievalHelperAdapter extends BeanFactoryAdvisorRetrievalHelper {

		public BeanFactoryAdvisorRetrievalHelperAdapter(ConfigurableListableBeanFactory beanFactory) {
			super(beanFactory);
		}

		@Override
		protected boolean isEligibleBean(String beanName) {
		//isEligibleAdvisorBean不同的子类来决定
			return AbstractAdvisorAutoProxyCreator.this.isEligibleAdvisorBean(beanName);
		}
	}
}
BeanFactoryAdvisorRetrievalHelper

用于从 BeanFactory 检索标准 Spring Advisor 的助手,用于自动代理。

public class BeanFactoryAdvisorRetrievalHelper {

	private static final Log logger = LogFactory.getLog(BeanFactoryAdvisorRetrievalHelper.class);

	private final ConfigurableListableBeanFactory beanFactory;

	@Nullable
	private volatile String[] cachedAdvisorBeanNames;

	public BeanFactoryAdvisorRetrievalHelper(ConfigurableListableBeanFactory beanFactory) {
		Assert.notNull(beanFactory, "ListableBeanFactory must not be null");
		this.beanFactory = beanFactory;
	}

	/**
	 * Find all eligible Advisor beans in the current bean factory,
	 * ignoring FactoryBeans and excluding beans that are currently in creation.
	 */
	public List<Advisor> findAdvisorBeans() {
		// Determine list of advisor bean names, if not cached already.
		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!
			//容器中查询出所有类型WieAdvisor类型的bean
			advisorNames = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(
					this.beanFactory, Advisor.class, true, false);
			this.cachedAdvisorBeanNames = advisorNames;
		}
		if (advisorNames.length == 0) {
			return new ArrayList<>();
		}

		List<Advisor> advisors = new ArrayList<>();
		for (String name : advisorNames) {
		//isEligibleBean最终是由AbstractAdvisorAutoProxyCreator#isEligibleAdvisorBean方法决定的,该方法需要由AbstractAdvisorAutoProxyCreator的子类重写来决定最终返回结果
			if (isEligibleBean(name)) {
			//不会吧正在创建中的advisor加入集合
				if (this.beanFactory.isCurrentlyInCreation(name)) {
					if (logger.isTraceEnabled()) {
						logger.trace("Skipping currently created advisor '" + name + "'");
					}
				}
				else {
					try {
					//加入集合
						advisors.add(this.beanFactory.getBean(name, Advisor.class));
					}
					catch (BeanCreationException ex) {
						Throwable rootCause = ex.getMostSpecificCause();
						if (rootCause instanceof BeanCurrentlyInCreationException) {
							BeanCreationException bce = (BeanCreationException) rootCause;
							String bceBeanName = bce.getBeanName();
							if (bceBeanName != null && this.beanFactory.isCurrentlyInCreation(bceBeanName)) {
								if (logger.isTraceEnabled()) {
									logger.trace("Skipping advisor '" + name +
											"' with dependency on currently created bean: " + ex.getMessage());
								}
								// Ignore: indicates a reference back to the bean we're trying to advise.
								// We want to find advisors other than the currently created bean itself.
								continue;
							}
						}
						throw ex;
					}
				}
			}
		}
		return advisors;
	}

	/**
	 * Determine whether the aspect bean with the given name is eligible.
	 * <p>The default implementation always returns {@code true}.
	 * @param beanName the name of the aspect bean
	 * @return whether the bean is eligible
	 */
	protected boolean isEligibleBean(String beanName) {
		return true;
	}

}
DefaultAdvisorAutoProxyCreator—isEligibleAdvisorBean

打个比方:它就是BeanNameAutoProxyCreator的加强版。如果说BeanNameAutoProxyCreator就是步枪需要自己装配,DefaultAdvisorAutoProxyCreator就是自动步枪了,Spring可以完成自动匹配的工作了

一般,我们只需要这样配置即可

@Bean
    public DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator() {
        return new DefaultAdvisorAutoProxyCreator();
    }

	// 还需要对应的Advisor(可以有多个~~)  从而给能够匹配上的创建代理对象了
    @Bean
    public NameMatchMethodPointcutAdvisor nameMatchMethodPointcutAdvisor() {
        NameMatchMethodPointcutAdvisor nameMatchMethodPointcutAdvisor = new NameMatchMethodPointcutAdvisor();
        
        //拦截到了HelloService#hello()方法,因此会给他创建代理对象
        nameMatchMethodPointcutAdvisor.addMethodName("*hello");
        
        // 请注意:此处虽然HelloController有个方法名叫helloGet,但是不会创建代理得。因为这在根容器里,这种情况不作用与子容器的Bean的
        nameMatchMethodPointcutAdvisor.addMethodName("helloGet"); 
        nameMatchMethodPointcutAdvisor.setAdvice(new MyMethodInteceptor());
        return nameMatchMethodPointcutAdvisor;
    }

这样它就会自动的去把Advisor匹配上的Bean进行代理掉。(不像BeanNameAutoProxyCreator还得手动指定BeanName,以及拦截器们)

一般都需要自己像容器注入自己的Advisor,比如NameMatchMethodPointcutAdvisor,否则它也不知道去代理谁嘛。只有被对应的Advisor匹配上的才会生成代理对象

源码:

public class DefaultAdvisorAutoProxyCreator extends AbstractAdvisorAutoProxyCreator implements BeanNameAware {

	/** Separator between prefix and remainder of bean name. */
	public static final String SEPARATOR = ".";

	private boolean usePrefix = false;

	@Nullable
	private String advisorBeanNamePrefix;

	/**
	 * Set whether to only include advisors with a certain prefix in the bean name.
	 * <p>Default is {@code false}, including all beans of type {@code Advisor}.
	 * @see #setAdvisorBeanNamePrefix
	 */
	public void setUsePrefix(boolean usePrefix) {
		this.usePrefix = usePrefix;
	}

	/**
	 * Return whether to only include advisors with a certain prefix in the bean name.
	 */
	public boolean isUsePrefix() {
		return this.usePrefix;
	}

	/**
	 * Set the prefix for bean names that will cause them to be included for
	 * auto-proxying by this object. This prefix should be set to avoid circular
	 * references. Default value is the bean name of this object + a dot.
	 * @param advisorBeanNamePrefix the exclusion prefix
	 */
	public void setAdvisorBeanNamePrefix(@Nullable String advisorBeanNamePrefix) {
		this.advisorBeanNamePrefix = advisorBeanNamePrefix;
	}

	/**
	 * Return the prefix for bean names that will cause them to be included
	 * for auto-proxying by this object.
	 */
	@Nullable
	public String getAdvisorBeanNamePrefix() {
		return this.advisorBeanNamePrefix;
	}

	@Override
	public void setBeanName(String name) {
		// If no infrastructure bean name prefix has been set, override it.
		if (this.advisorBeanNamePrefix == null) {
			this.advisorBeanNamePrefix = name + SEPARATOR;
		}
	}

	// Consider {@code Advisor} beans with the specified prefix as eligible, if activated.
	// 用到了前缀之类的。主要是考虑可以通过前缀匹配某一类Bean,而其他的Advisor我就不匹配了
	// 前缀的作用:进行分离匹配(而不是拿所有的Advisor~~)
	@Override
	protected boolean isEligibleAdvisorBean(String beanName) {
		if (!isUsePrefix()) {
			return true;
		}
		String prefix = getAdvisorBeanNamePrefix();
		return (prefix != null && beanName.startsWith(prefix));
	}

}

对于Advisor的自动探测功能,在父类AbstractAdvisorAutoProxyCreator中统一完成

InfrastructureAdvisorAutoProxyCreator----isEligibleAdvisorBean

Infrastructure:基础设施、基建

听这名字就知道,这是Spring给自己内部使用的一个自动代理创建器。这个类在@EnableTransactionManagement事务相关里会再次提到(它的AutoProxyRegistrar就是向容器注册了它),其实它的作用非常简单:主要是读取Advisor类,并对符合的bean进行二次代理

public class InfrastructureAdvisorAutoProxyCreator extends AbstractAdvisorAutoProxyCreator {

	@Nullable
	private ConfigurableListableBeanFactory beanFactory;

	@Override
	protected void initBeanFactory(ConfigurableListableBeanFactory beanFactory) {
		super.initBeanFactory(beanFactory);
		this.beanFactory = beanFactory;
	}
	
     // 没有其余多余代码 就这一个
	// bean工厂含有这个Bean,且这个Bean的Role是BeanDefinition.ROLE_INFRASTRUCTURE 系统内部用的  才返回true
	@Override
	protected boolean isEligibleAdvisorBean(String beanName) {
		return (this.beanFactory != null && this.beanFactory.containsBeanDefinition(beanName) &&
				this.beanFactory.getBeanDefinition(beanName).getRole() == BeanDefinition.ROLE_INFRASTRUCTURE);
	}

}
AspectJAwareAdvisorAutoProxyCreator

顾名思义,该类主要来处理AspectJ切面的。这也是当下最流行,也是功能最为强大的一种方式吧~~~

它对父类,做了如下几点扩展:

// @since 2.0
public class AspectJAwareAdvisorAutoProxyCreator extends AbstractAdvisorAutoProxyCreator {

	// 默认的排序器,它就不是根据Order来了,而是根据@Afeter @Before类似的标注来排序
	private static final Comparator<Advisor> DEFAULT_PRECEDENCE_COMPARATOR = new AspectJPrecedenceComparator();

	// 核心逻辑:它重写了排序
	// 这个排序和`org.aspectj.util`提供的PartialOrder和PartialComparable有关 具体不详叙了
	// 这块排序算法还是比较复杂的,控制着最终的执行顺序~
	protected List<Advisor> sortAdvisors(List<Advisor> advisors) {
		...
	}

	// 这个就是对已有的Advisor做了一个扩展:
	// AspectJProxyUtils这个工具类只有这一个方法  (其实每次addAspect()的时候,都会调用此方法)
	// Capable:能干的  有才华的
	// 它的作用:(若存在AspectJ的Advice),就会在advisors的第一个位置加入`ExposeInvocationInterceptor.ADVISOR`这个advisor
	@Override
	protected void extendAdvisors(List<Advisor> candidateAdvisors) {
		AspectJProxyUtils.makeAdvisorChainAspectJCapableIfNecessary(candidateAdvisors);
	}

	
	// 这个相当于:
	@Override
	protected boolean shouldSkip(Class<?> beanClass, String beanName) {
		List<Advisor> candidateAdvisors = findCandidateAdvisors();
		
		// 这个相当于AspectJPointcutAdvisor的子类不要拦截、AspectJ切面自己自己的所有方法不要去拦截。。。
		for (Advisor advisor : candidateAdvisors) {
			if (advisor instanceof AspectJPointcutAdvisor &&
					((AspectJPointcutAdvisor) advisor).getAspectName().equals(beanName)) {
				return true;
			}
		}
		// 父类返回的false
		return super.shouldSkip(beanClass, beanName);
	}
	...
}

ExposeInvocationInterceptor 的作用是用于暴露 MethodInvocation 对象到 ThreadLocal 中,其名字也体现出了这一点。

如果其他地方需要当前的 MethodInvocation 对象,直接通过调用静态方法 ExposeInvocationInterceptor.currentInvocation 方法取出。那哪些地方会用到呢????

AspectJExpressionPointcut#matches就有用到~~

AnnotationAwareAspectJAutoProxyCreator

首先AnnotationAwareAspectJAutoProxyCreator它是AspectJAwareAdvisorAutoProxyCreator的子类。

然后从名字中可议看出,它和注解有关。因此其实我们的@EnableAspectJAutoProxy它导入的就是这个自动代理创建器去帮我们创建和AspectJ相关的代理对象的。这也是我们当下使用最为广泛的方式~

// @since 2.0
public class AnnotationAwareAspectJAutoProxyCreator extends AspectJAwareAdvisorAutoProxyCreator {

	@Nullable
	private List<Pattern> includePatterns;
	//唯一实现类:ReflectiveAspectJAdvisorFactory
	// 作用:基于@Aspect时,创建Spring AOP的Advice
	// 里面会对标注这些注解Around.class, Before.class, After.class, AfterReturning.class, AfterThrowing.class的方法进行排序
	// 然后把他们都变成Advisor( getAdvisors()方法 )
	@Nullable
	private AspectJAdvisorFactory aspectJAdvisorFactory;
	//该工具类用来从bean容器,也就是BeanFactory中获取所有使用了@AspectJ注解的bean
	//就是这个方法:aspectJAdvisorsBuilder.buildAspectJAdvisors()
	@Nullable
	private BeanFactoryAspectJAdvisorsBuilder aspectJAdvisorsBuilder;

	// 很显然,它还支持我们自定义一个正则的模版
	// isEligibleAspectBean()该方法使用此模版,从而决定使用哪些Advisor
	public void setIncludePatterns(List<String> patterns) {
		this.includePatterns = new ArrayList<>(patterns.size());
		for (String patternText : patterns) {
			this.includePatterns.add(Pattern.compile(patternText));
		}
	}
	
	// 可以自己实现一个AspectJAdvisorFactory  否则用默认的ReflectiveAspectJAdvisorFactory
	public void setAspectJAdvisorFactory(AspectJAdvisorFactory aspectJAdvisorFactory) {
		Assert.notNull(aspectJAdvisorFactory, "AspectJAdvisorFactory must not be null");
		this.aspectJAdvisorFactory = aspectJAdvisorFactory;
	}

	// 此处一定要记得调用:super.initBeanFactory(beanFactory);
	@Override
	protected void initBeanFactory(ConfigurableListableBeanFactory beanFactory) {
		super.initBeanFactory(beanFactory);
		if (this.aspectJAdvisorFactory == null) {
			this.aspectJAdvisorFactory = new ReflectiveAspectJAdvisorFactory(beanFactory);
		}
		this.aspectJAdvisorsBuilder = new BeanFactoryAspectJAdvisorsBuilderAdapter(beanFactory, this.aspectJAdvisorFactory);
	}

	// 拿到所有的候选的advisor们。请注意:这里没有先调用了父类的super.findCandidateAdvisors()  去容器里找出来一些
	// 然后,然后自己又通过aspectJAdvisorsBuilder.buildAspectJAdvisors()  解析@Aspect的方法得到一些Advisor
	@Override
	protected List<Advisor> findCandidateAdvisors() {
		List<Advisor> advisors = super.findCandidateAdvisors();
		if (this.aspectJAdvisorsBuilder != null) {
			advisors.addAll(this.aspectJAdvisorsBuilder.buildAspectJAdvisors());
		}
		return advisors;
	}
	
	// 加了中类型   如果该Bean自己本身就是一个@Aspect, 那也认为是基础主键,不要切了
	@Override
	protected boolean isInfrastructureClass(Class<?> beanClass) {
		return (super.isInfrastructureClass(beanClass) ||
				(this.aspectJAdvisorFactory != null && this.aspectJAdvisorFactory.isAspect(beanClass)));
	}

	// 拿传入的正则模版进行匹配(没传就返回true,所有的Advisor都会生效)
	protected boolean isEligibleAspectBean(String beanName) {
		if (this.includePatterns == null) {
			return true;
		}
		else {
			for (Pattern pattern : this.includePatterns) {
				if (pattern.matcher(beanName).matches()) {
					return true;
				}
			}
			return false;
		}
	}

	private class BeanFactoryAspectJAdvisorsBuilderAdapter extends BeanFactoryAspectJAdvisorsBuilder {

		public BeanFactoryAspectJAdvisorsBuilderAdapter(
				ListableBeanFactory beanFactory, AspectJAdvisorFactory advisorFactory) {

			super(beanFactory, advisorFactory);
		}

		@Override
		protected boolean isEligibleBean(String beanName) {
			return AnnotationAwareAspectJAutoProxyCreator.this.isEligibleAspectBean(beanName);
		}
	}

}

AspectJAwareAdvisorAutoProxyCreator它用于xml配置版的AspectJ切面自动代理创建(< aop:config/>)

AnnotationAwareAspectJAutoProxyCreator用于基于注解的自动代理创建(< aop:aspectj-autoproxy/> 或 @EnableAspectJAutoProxy)

BeanFactoryAspectJAdvisorsBuilder
public class BeanFactoryAspectJAdvisorsBuilder {

	private final ListableBeanFactory beanFactory;

	private final AspectJAdvisorFactory advisorFactory;

	@Nullable
	private volatile List<String> aspectBeanNames;

	private final Map<String, List<Advisor>> advisorsCache = new ConcurrentHashMap<>();

	private final Map<String, MetadataAwareAspectInstanceFactory> aspectFactoryCache = new ConcurrentHashMap<>();

	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 = advisorFactory;
	}

	/**
	 * Look for AspectJ-annotated aspect beans in the current bean factory,
	 * and return to a list of Spring AOP Advisors representing them.
	 * Creates a Spring Advisor for each AspectJ advice method.
	 */
	public List<Advisor> buildAspectJAdvisors() {
		List<String> aspectNames = this.aspectBeanNames;

		if (aspectNames == null) {
			synchronized (this) {
				aspectNames = this.aspectBeanNames;
				if (aspectNames == null) {
					List<Advisor> advisors = new ArrayList<>();
					aspectNames = new ArrayList<>();
					//拿到容器中所有bean
					String[] beanNames = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(
							this.beanFactory, Object.class, true, false);
					for (String beanName : beanNames) {
					//可以使用我们设置的includePatterns先进行过滤
					//不管是不是切面,如果正则匹配不上,那么就算是切面,也不行
						if (!isEligibleBean(beanName)) {
							continue;
						}
						// We must be careful not to instantiate beans eagerly as in this case they
						// would be cached by the Spring container but would not have been weaved.
						Class<?> beanType = this.beanFactory.getType(beanName, false);
						if (beanType == null) {
							continue;
						}
						//然后再按照bean上标注了Aspect注解的方式进行过滤
						if (this.advisorFactory.isAspect(beanType)) {
							aspectNames.add(beanName);
							//构造切面元数据
							AspectMetadata amd = new AspectMetadata(beanType, beanName);
							//切面默认都为单例--这里的单例不是指spring的scope,而是aspectj特有的
							if (amd.getAjType().getPerClause().getKind() == PerClauseKind.SINGLETON) {
							//切面工厂,并提供获取切面元数据的方法
								MetadataAwareAspectInstanceFactory factory =
										new BeanFactoryAspectInstanceFactory(this.beanFactory, beanName);
							//将切面解析为一组增强器集合---AspectJ是高级切面,里面可以包含很多个advice
							//但是最终还是要转换为低级切面,每个advisor里面只能有一个advice			
								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 ArrayList<>();
		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;
	}

	protected boolean isEligibleBean(String beanName) {
		return true;
	}

}

相关文章