五Spring-AOP--5AOP初始化源码分析

五Spring-AOP--5AOP初始化源码分析

5.6 AOP源码分析

5.6.1 AOP初始化

AOP入口位置,在初始化方法中:

TAG0.1 AbstractAutowireCapableBeanFactory.initializeBean()
	protected Object initializeBean(final String beanName, final Object bean, @Nullable RootBeanDefinition mbd) {
		if (System.getSecurityManager() != null) {
			AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
				invokeAwareMethods(beanName, bean);
				return null;
			}, getAccessControlContext());
		}
		else {

//DCB5.1 invokeAwareMethods
               //调用aware接口,设置bean的classloader、beanname、beanfactory等信息
               //该处调用的就是aware接口的setXXX方法
			invokeAwareMethods(beanName, bean);
		}

		Object wrappedBean = bean;
		if (mbd == null || !mbd.isSynthetic()) {
      
//DCB5.2 applyBeanPostProcessorsBeforeInitialization---7pp
               //特殊注解的支持:@postContrust,Aware接口
               /** aop入口在此!
               所有aop切面的父类AbstractAutoProxyCreator
               有几个aop的入口类:基于配置的,基于注解的
               */
			wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
		}

		try {
//DCB5.3 invokeInitMethods
               //initializingBean接口,afterPropertiesSet方法,init-method等属性调用点
               //after调用时机早于init-method
			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()) {
      
/** ……………………………………………………………………………………AOP入口……………………………………………………………………………………*/
//TAG0.2 applyBeanPostProcessorsAfterInitialization
//DCB5.4 applyBeanPostProcessorsAfterInitialization---8pp
               //为bean实例初始化之后,做一些处理
      			//AOP入口
			wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
		}

		return wrappedBean;
	}
TAG0.2 applyBeanPostProcessorsAfterInitialization
@Override
	public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName)
			throws BeansException {

		Object result = existingBean;
		for (BeanPostProcessor processor : getBeanPostProcessors()) {
      //调用后置处理器的postProcessAfterInitialization方法
			Object current = processor.postProcessAfterInitialization(result, beanName);
			if (current == null) {
				return result;
			}
			result = current;
		}
		return result;
	}

AOP的初始化入口位置,在bean的初始化后处理的阶段。

image-20230310123249966

AbstractAutoProxyCreator是整个Spring AOP模块的协作组件,它作为AOP的指挥官角色,统一协作Advisor(切面)和AopProxy(动态代理)这两大核心组件。它的本质是BeanPostProcessor(后置处理器)的一种实现,通过Spring IOC模块来启动运行。它针对的主体是Spring的Bean对象。

image-20230310123306254

类继承关系图,AbstractAutoProxyCreator是BeanPostProcessor和InstationAwareBeanPostProcessor的实现类,因此其可以在bean的实例化和初始化前后执行处理方法。

AOP的入口方法,由AbstractAutoProxyCreator实现postProcessAfterInitialization完成:

AbstractAutoProxyCreator
public Object postProcessAfterInitialization(@Nullable Object bean, String beanName) {
		if (bean != null) { //1 
      //获取bean的类Class对象(对普通bean还是FactoryBean的处理),该Clazz对象作为key
			Object cacheKey = getCacheKey(bean.getClass(), beanName);

      /** Map<Object, Object> earlyProxyReferences = new ConcurrentHashMap<>(16),cacheKey为需要代理的Clazz类,bean为缓存入的AOP增强过后的对象 */
      //缓存,该处的判断保证对bean的增强操作,幂等(只操作一次)
      //判断逻辑:如果==bean,表示当前类已经被增强过,且缓存增强后的bean与传入的bean相同,不再AOP处理,直接返回
			if (this.earlyProxyReferences.remove(cacheKey) != bean) {
        
/** ……………………………………………………………………AOP封装的核心…………………………………………………………………………………………*/
//TAG0.3 wrapIfNecessary
				return wrapIfNecessary(bean, beanName, cacheKey);
			}
		} //1 
		return bean;
	}

初始化后置处理,对bean进行AOP增强的幂等性判断,然后执行AOP封装核心方法

TAG0.3 wrapIfNecessary
AbstractAutoProxyCreator{
//记录Clazz对象是否需要增强的map,object为bean.getClass,boolean表示是否需要增强
private final Map<Object, Boolean> advisedBeans = new ConcurrentHashMap<>(256);

protected Object wrapIfNecessary(Object bean, String beanName, Object cacheKey) {
		if (StringUtils.hasLength(beanName) && this.targetSourcedBeans.contains(beanName)) {
			return bean;
		}
  	//如果不需要增强,直接返回bean
		if (Boolean.FALSE.equals(this.advisedBeans.get(cacheKey))) {
			return bean;
		}
  	//如果bean为AopInfrastructureBean实现类,不AOP增强,不产生AOP代理类
		if (isInfrastructureClass(bean.getClass()) || shouldSkip(bean.getClass(), beanName)) {
			this.advisedBeans.put(cacheKey, Boolean.FALSE);
			return bean;
		}

//TAG1 getAdvicesAndAdvisorsForBean
		// Create proxy if we have advice.
  	//从beanFactory中找出所有的Advisor.class类型的类,并过滤出可以作用于当前bean的advisor集合
		Object[] specificInterceptors = getAdvicesAndAdvisorsForBean(bean.getClass(), beanName, null);
  	//当指定的拦截器不为DO_NOT_PROXY(null)时
		if (specificInterceptors != DO_NOT_PROXY) {
			this.advisedBeans.put(cacheKey, Boolean.TRUE);
      
//TAG2 createProxy
//根据拦截器specificInterceptors、目标类SingletonTargetSource,创建代理对象(AOP代理对象)
      //SingletonTargetSource(bean)封装被代理对象
			Object proxy = createProxy(
					bean.getClass(), beanName, specificInterceptors, new SingletonTargetSource(bean));
			this.proxyTypes.put(cacheKey, proxy.getClass());
			return proxy;
		}

  	//不需要创建aop代理类
		this.advisedBeans.put(cacheKey, Boolean.FALSE);
		return bean;
	}
TAG1 getAdvicesAndAdvisorsForBean

注意:

这里是从beanFactory中,找出所有的Advisor.class类型的类,并过滤出可以作用于当前bean的advisor集合

image-20221108221151894

AbstractAdvisorAutoProxyCreator

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

  	//找到符合条件的advisor(可以作用于beanClass这个Class类上的advisor的list)
//TAG1.1 findEligibleAdvisors
		List<Advisor> advisors = findEligibleAdvisors(beanClass, beanName);
		if (advisors.isEmpty()) {
			return DO_NOT_PROXY;
		}
		return advisors.toArray();
	}

继续跟进代码

TAG1.1 findEligibleAdvisors
AbstractAdvisorAutoProxyCreator		//这个方法,由子类实现

protected List<Advisor> findEligibleAdvisors(Class<?> beanClass, String beanName) {
  
//TAG1.1.1 findCandidateAdvisors
  	//找到标记@Aspect注解的切面,并封装成List<Advisor>
		List<Advisor> candidateAdvisors = findCandidateAdvisors();
  
//TAG1.1.2 findAdvisorsThatCanApply
  	//过滤出需要再当前beanclass上增强的advisor集合
		List<Advisor> eligibleAdvisors = findAdvisorsThatCanApply(candidateAdvisors, beanClass, beanName);
		extendAdvisors(eligibleAdvisors);
		if (!eligibleAdvisors.isEmpty()) {
      //如果切面advisor有@Order或者@Priority注解,对切面排序
			eligibleAdvisors = sortAdvisors(eligibleAdvisors);
		}
		return eligibleAdvisors;
	}
TAG1.1.1 findCandidateAdvisors---beanFactory中的Advisor

然后,调用方法findCandidateAdvisors,找到自动代理需要用到的,所有候选的advisors。

AbstractAdvisorAutoProxyCreator

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


BeanFactoryAdvisorRetrievalHelper

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!
      //找到beanFactory中的Advisor类型的所有类、子类的名称(刨除FactoryBeans)
			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) { //1 
      //判定给定名称的advisor是否是符合条件的---方法见下面
//TAG1.1.1.1 isEligibleBean
			if (isEligibleBean(name)) { //2 
        
        //如果当前bean正在创建中,跳过正在创建过程中的advisor对象
				if (this.beanFactory.isCurrentlyInCreation(name)) { //3
					if (logger.isTraceEnabled()) {
						logger.trace("Skipping currently created advisor '" + name + "'");
					}
				} //3 
				else { //3
					try { 
            
/**………………………………………………………………………………从beanFactory中找出所有的Advisor…………………………………………………………………… */
            //从beanFactory中获取name的bean,作为advisor加入list中
						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;
					}
				} //3
			} //2 
		} //1 
		return advisors;
	}
TAG1.1.1.1 isEligibleBean

isEligibleBean的方法实现,由AbstractAdvisorAutoProxyCreator内部类实现

AbstractAdvisorAutoProxyCreator

private class BeanFactoryAdvisorRetrievalHelperAdapter extends BeanFactoryAdvisorRetrievalHelper {

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

		@Override
		protected boolean isEligibleBean(String beanName) {
			return AbstractAdvisorAutoProxyCreator.this.isEligibleAdvisorBean(beanName);
		}
	}
DefaultAdvisorAutoProxyCreator

protected boolean isEligibleAdvisorBean(String beanName) {
		if (!isUsePrefix()) {
			return true;
		}
		String prefix = getAdvisorBeanNamePrefix();
		return (prefix != null && beanName.startsWith(prefix));
	}
	
	public String getAdvisorBeanNamePrefix() {
		return this.advisorBeanNamePrefix;
	}

isEligibleBean的实现逻辑,是判断当前advisor以特定的prefix为前缀。

TAG1.1.2 findAdvisorsThatCanApply

该方法,从给定的candidateAdvisors中找到可以应用到指定的beanclass上的List.

AbstractAdvisorAutoProxyCreator

protected List<Advisor> findAdvisorsThatCanApply(
			List<Advisor> candidateAdvisors, Class<?> beanClass, String beanName) {
		
  	//ThreadLocal<String>保存的当前正在被代理的bean(该ThreadLocal仅仅在Advisor匹配时,保存当前被代理bean)
		ProxyCreationContext.setCurrentProxiedBeanName(beanName);
		try {
      //匹配当前beanclass对应的advisors
			return AopUtils.findAdvisorsThatCanApply(candidateAdvisors, beanClass);
		}
		finally {
			ProxyCreationContext.setCurrentProxiedBeanName(null);
		}
	}
AopUtils

	public static List<Advisor> findAdvisorsThatCanApply(List<Advisor> candidateAdvisors, Class<?> clazz) {
		if (candidateAdvisors.isEmpty()) {
			return candidateAdvisors;
		}
		List<Advisor> eligibleAdvisors = new ArrayList<>();
		for (Advisor candidate : candidateAdvisors) { //1 
      
//TAG1.1.2.1 canApply(candidate, clazz)
      //即是引介类型的advisor,且能canApply
			if (candidate instanceof IntroductionAdvisor && canApply(candidate, clazz)) { //2 
				eligibleAdvisors.add(candidate);
			} //2 
		} //1 
  
  	//判断当前是否有引介类型的IntroductionAdvisor
		boolean hasIntroductions = !eligibleAdvisors.isEmpty();
		for (Advisor candidate : candidateAdvisors) { //1 
			if (candidate instanceof IntroductionAdvisor) { 
				// already processed 已经处理过
				continue;
			}
//TAG1.1.2.2 canApply(candidate, clazz, hasIntroductions)
      //针对PointcutAdvisor类型的,如果canApply
			if (canApply(candidate, clazz, hasIntroductions)) {
				eligibleAdvisors.add(candidate);
			}
		} //1 
		return eligibleAdvisors;
	}
image-20221109172036949
TAG1.1.2.1 canApply(candidate, clazz)
public static boolean canApply(Advisor advisor, Class<?> targetClass) {
		//第三个参数,hasIntroductions位false
		return canApply(advisor, targetClass, false);
	}
	
	//第三个参数,表示当前target的advisor chain,是否包含引介类型的advisor
	public static boolean canApply(Advisor advisor, Class<?> targetClass, boolean hasIntroductions) {
    
    //advisor引介类型
		if (advisor instanceof IntroductionAdvisor) {
      //调用classfilter的match,匹配当前targetclass
			return ((IntroductionAdvisor) advisor).getClassFilter().matches(targetClass);
		}
    //PointcutAdvisor类型
		else if (advisor instanceof PointcutAdvisor) {
			PointcutAdvisor pca = (PointcutAdvisor) advisor;
      //调用封装方法匹配
			return canApply(pca.getPointcut(), targetClass, hasIntroductions);
		}
		else {
			// It doesn't have a pointcut so we assume it applies.
			return true;
		}
	}
public static boolean canApply(Pointcut pc, Class<?> targetClass, boolean hasIntroductions) {
		Assert.notNull(pc, "Pointcut must not be null");
  	//首先,Pointcut.ClassFilter的matches(targetclass)方法,判断当前类是否能被pointcut拦截
		if (!pc.getClassFilter().matches(targetClass)) {
      //classfilter.match匹配失败
			return false;
		}

  	//获取Pointcut.methodMatcher
		MethodMatcher methodMatcher = pc.getMethodMatcher();
		if (methodMatcher == MethodMatcher.TRUE) {
			// No need to iterate the methods if we're matching any method anyway...
			return true;
		}

		IntroductionAwareMethodMatcher introductionAwareMethodMatcher = null;
		if (methodMatcher instanceof IntroductionAwareMethodMatcher) {
			introductionAwareMethodMatcher = (IntroductionAwareMethodMatcher) methodMatcher;
		}

		Set<Class<?>> classes = new LinkedHashSet<>();
		if (!Proxy.isProxyClass(targetClass)) {
			classes.add(ClassUtils.getUserClass(targetClass));
		}
  	//获取targetclass的所有的接口,存入classes中
		classes.addAll(ClassUtils.getAllInterfacesForClassAsSet(targetClass));
		
  	//遍历targetclass的所有父类(包括接口)
		for (Class<?> clazz : classes) {
      //获取每个父类中声明的方法
			Method[] methods = ReflectionUtils.getAllDeclaredMethods(clazz);
      //遍历method
			for (Method method : methods) {
				if (introductionAwareMethodMatcher != null ?
            //引介类型的方法匹配
						introductionAwareMethodMatcher.matches(method, targetClass, hasIntroductions) :
            //pointcutadvisor内methodmatcher的匹配
						methodMatcher.matches(method, targetClass)) {
					return true;
				}
			}
		}

		return false;
	}

canApply的执行逻辑:

1 从Pointcut.ClassFilter的matches(targetclass)方法,判断当前目标类,是否被切面拦截;

2 如果当前目标类被切面拦截,需要增强,然后判断targetclass的方法,是否被切面拦截

​ 2.1 分别获取targetclass的所有classes,遍历classes,获取所有的声明的方法,并遍历;

​ 2.2 对遍历的每个方法对象method,执行Pointcut.MethodMatcher的matches方法,进行匹配。

TAG1.1.2.2 canApply(candidate, clazz, hasIntroductions)

见上。hasIntroductions参数,代表当前的targetclass的advisor的chain中,是否有引介类型的advisor。

TAG2 createProxy
AbstractAutoProxyCreator{
//TAG2 createProxy
//根据拦截器specificInterceptors、目标类SingletonTargetSource,创建代理对象(AOP代理对象)
      //SingletonTargetSource(bean)封装被代理对象
			Object proxy = createProxy(
					bean.getClass(), beanName, specificInterceptors, new SingletonTargetSource(bean));
			this.proxyTypes.put(cacheKey, proxy.getClass());
			return proxy;

调用createProxy方法,以及拦截器specificInterceptors(上面过程过滤过对当前bean有增强作用的切面)、SingletonTargetSource包裹目标类等参数,创建代理类。

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

//TAG2.1 new ProxyFactory
  	//创建代理工厂proxyFactory,通过proxyFactory.getProxy创建AOP代理对象
		ProxyFactory proxyFactory = new ProxyFactory();
  //复制AbstractAutoProxyCreator的信息到proxyfactory
		proxyFactory.copyFrom(this);

/**…………………………………………………………………………设置proxyfactory代理模式……………………………………………………………………………………
**proxyfactory代理模式的规则如下:**
1、当proxyTargetClass为true时,目标bean实现了接口或只有实现类都采用Cglib做动态代理;
2、当proxyTargetClass为false时,目标bean若实现了接口则采用JDK内置代理模式, 若目标bean只有实现类,则采用Cglib类代理模式;
3、默认proxyTargetClass为false;*/
  
  	//proxyFactory的isProxyTargetClass为ture,表示,proxyfactory是否直接代理targetclass以及所有接口
		if (proxyFactory.isProxyTargetClass()) {
			// Explicit handling of JDK proxy targets and lambdas (for introduction advice scenarios)
			if (Proxy.isProxyClass(beanClass) || ClassUtils.isLambdaClass(beanClass)) {
				// Must allow for introductions; can't just set interfaces to the proxy's interfaces only.
				for (Class<?> ifc : beanClass.getInterfaces()) {
          //添加beanClass的所有接口interfaces,到proxyfactory内
					proxyFactory.addInterface(ifc);
				}
			}
		}
		else {
			// No proxyTargetClass flag enforced, let's apply our default checks...
      //如果should代理TargetClass设置为true
			if (shouldProxyTargetClass(beanClass, beanName)) {
				proxyFactory.setProxyTargetClass(true);
			}
			else {
//TAG2.2 evaluateProxyInterfaces
        //JDK代理,评估代理接口
				evaluateProxyInterfaces(beanClass, proxyFactory);
			}
		}

//TAG2.3 buildAdvisors
		Advisor[] advisors = buildAdvisors(beanName, specificInterceptors);
		proxyFactory.addAdvisors(advisors);
  	//设置代理的目标类--这里是SingletonTargetSource(bean)
		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();
		}
//TAG2.4 proxyFactory.getProxy(classLoader)
		return proxyFactory.getProxy(classLoader);
	}

TAG2.1 new ProxyFactory
image-20230310123402227

在AbstractAutoProxyCreator中,创建ProxyFactory对象,后面调用ProxyFactory.getProxy方法得到代理对象。

proxyfactory类,保存了当前被代理对象targetsource、代理接口interfaces、作用于targetclass上的advisors等信息。其主要的功能方法和属性,如下所示:

image-20230310123420183

然后,调用copyFrom方法,复制AbstractAutoProxyCreator上的代理信息,到当前proxyfactory上。

ProxyConfig
public void copyFrom(ProxyConfig other) {
		Assert.notNull(other, "Other ProxyConfig object must not be null");
		this.proxyTargetClass = other.proxyTargetClass;
		this.optimize = other.optimize;
		this.exposeProxy = other.exposeProxy;
		this.frozen = other.frozen;
		this.opaque = other.opaque;
	}
TAG2.2 evaluateProxyInterfaces--设置代理模式

proxyfactory代理模式的规则如下:

1、当proxyTargetClass为true时,目标bean实现了接口或只有实现类都采用Cglib做动态代理;

2、当proxyTargetClass为false时,目标bean若实现了接口则采用JDK内置代理模式, 若目标bean只有实现类,则采用Cglib类代理模式;

3、默认proxyTargetClass为false;

public class ProxyProcessorSupport extends ProxyConfig implements Ordered, BeanClassLoaderAware, AopInfrastructureBean {

	// 这是它提供的一个最为核心的方法:这里决定了如果目标类没有实现接口直接就是Cglib代理
	// 检查给定beanClass上的接口们,并交给proxyFactory处理
	protected void evaluateProxyInterfaces(Class<?> beanClass, ProxyFactory proxyFactory) {
		// 找到该类实现的所有接口们~~~
		Class<?>[] targetInterfaces = ClassUtils.getAllInterfacesForClass(beanClass, getProxyClassLoader());
			
		// 标记:是否有存在【合理的】接口~~~
		boolean hasReasonableProxyInterface = false;
		for (Class<?> ifc : targetInterfaces) { //1
			if (!isConfigurationCallbackInterface(ifc) && !isInternalLanguageInterface(ifc) &&
					// 如果所实现的接口,有一个接口有方法,就标识为,当前代理类beanclass有合理的代理接口
					ifc.getMethods().length > 0) { //2 
				hasReasonableProxyInterface = true;
				break;
			}//2 
		}	//1 
    
    //如果被代理类有合理的class接口
		if (hasReasonableProxyInterface) {
			// Must allow for introductions; can't just set interfaces to the target's interfaces only.
			// 这里Spring的Doc特别强调了:不能值只把合理的接口设置进去,而是都得加入进去
			for (Class<?> ifc : targetInterfaces) {
				proxyFactory.addInterface(ifc);
			}
		}
		else {
			// 这个很明显设置true,表示使用CGLIB得方式去创建代理了~~~~
			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"));
	}
}

这个方法,主要是评估beanClass的代理设置,判断是否当前beanClass是否有合理的接口,如果有将其添加入proxyfactory内;否则,设置proxyFactory.setProxyTargetClass(true),表示使用cglib创建代理对象。

TAG2.3 buildAdvisors--AOP核心

创建advisor的集合,为后续链式调用(增强)做准备。

AbstractAutoProxyCreator

  //specificInterceptors参数为TAG1中,找到的可以作用于当前bean的advisor集合
protected Advisor[] buildAdvisors(@Nullable String beanName, @Nullable Object[] specificInterceptors) {
  
//TAG2.3.1 resolveInterceptorNames
  	//解析@aspect注解的类,对象包装成advisor[]
		Advisor[] commonInterceptors = resolveInterceptorNames();

		List<Object> allInterceptors = new ArrayList<>();
  
  	//将TAG1 中过滤出,从beanFactory中获取的advisors,可以作用于当前bean的advisor集合,添加入allInterceptors
		if (specificInterceptors != null) {
			if (specificInterceptors.length > 0) {
				// specificInterceptors may equal PROXY_WITHOUT_ADDITIONAL_INTERCEPTORS
				allInterceptors.addAll(Arrays.asList(specificInterceptors));
			}
      //将从@Aspect中解析的advisor集合,添加入allInterceptors
			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++) {
//TAG2.3.2 advisorAdapterRegistry.wrap
      //将advice或者advisor包装成advisor
			advisors[i] = this.advisorAdapterRegistry.wrap(allInterceptors.get(i));
		}
		return advisors;
	}
TAG2.3.1 resolveInterceptorNames---@Aspect的advisor

注意:这里是解析包含@Aspect注解的类,并包装成Advisor集合。

AbstractAutoProxyCreator
	private Advisor[] resolveInterceptorNames() {
		BeanFactory bf = this.beanFactory;
		ConfigurableBeanFactory cbf = (bf instanceof ConfigurableBeanFactory ? (ConfigurableBeanFactory) bf : null);
		List<Advisor> advisors = new ArrayList<>();
//TAG2.3.1.2 this.interceptorNames
  //从@Aspect中解析的advice或advisor的名称
		for (String beanName : this.interceptorNames) {
			if (cbf == null || !cbf.isCurrentlyInCreation(beanName)) {
				Assert.state(bf != null, "BeanFactory required for resolving interceptor names");
        //从bf中获取beanName的advisor、advice对象
				Object next = bf.getBean(beanName);
//TAG2.3.2 advisorAdapterRegistry.wrap
        //通过advisorAdapterRegistry包装为advisor对象
				advisors.add(this.advisorAdapterRegistry.wrap(next));
			}
		}
		return advisors.toArray(new Advisor[0]);
	}
TAG2.3.1.2 this.interceptorNames--??

由@AspectJ注解的aspect,其中的拦截器(advice对象)会自动解析,然后调用AnnotationAwareAspectJAutoProxyCreator.setInterceptorNames方法,设置。

TAG2.3.2 advisorAdapterRegistry.wrap

将从beanFactory和@aspect中获得的advice或者advisor的集合,全部转换为List

public class DefaultAdvisorAdapterRegistry implements AdvisorAdapterRegistry, Serializable {
		//通知器适配器集合
	private final List<AdvisorAdapter> adapters = new ArrayList<>(3);
  
  
	// 默认就支持这几种类型的适配器(AdvisorAdapter能将advisor转换为AOP可以拦截识别的MethodInterceptor对象)
	public DefaultAdvisorAdapterRegistry() {
		registerAdvisorAdapter(new MethodBeforeAdviceAdapter());
		registerAdvisorAdapter(new AfterReturningAdviceAdapter());
		registerAdvisorAdapter(new ThrowsAdviceAdapter());
	}
  
  //将advice对象wrap包装转换为advisor对象
  @Override
	public Advisor wrap(Object adviceObject) throws UnknownAdviceTypeException {
/**…………………………………………………………待转换的为advisor的情况………………………………………………………………………………………… */
		if (adviceObject instanceof Advisor) {
			return (Advisor) adviceObject;
		}
		if (!(adviceObject instanceof Advice)) {
			throw new UnknownAdviceTypeException(adviceObject);
		}
    
/**…………………………………………………………待转换的为advice的情况………………………………………………………………………………………… */
		Advice advice = (Advice) adviceObject;
    //如果advice为MethodInterceptor
		if (advice instanceof MethodInterceptor) {
			//由于不需要advisorAdapter转换器,可之间构造advisor返回
			return new DefaultPointcutAdvisor(advice);
		}
    //如果advice为非MethodInterceptor的情况
		for (AdvisorAdapter adapter : this.adapters) {
			// Check that it is supported.
      //检测registry上所注册的advisorAdapter,是否有支持当前advice转换的,如果有,创建DefaultPointcutAdvisor
			if (adapter.supportsAdvice(advice)) {
				return new DefaultPointcutAdvisor(advice);
			}
		}
    //如果advisorAdapter没有支持转换advice的,则抛出异常
		throw new UnknownAdviceTypeException(advice);
	}
TAG2.4 proxyFactory.getProxy(classLoader)

动态代理对象的生成。

ProxyFactory

public Object getProxy(@Nullable ClassLoader classLoader) {
//TAG2.4.1 createAopProxy
//TAG2.4.2 getProxy
		return createAopProxy().getProxy(classLoader);
	}
TAG2.4.1 createAopProxy
protected final synchronized AopProxy createAopProxy() {
		if (!this.active) {
			activate();
		}
  //通过AopProxyFactory对象,创建AopProxy
		return getAopProxyFactory().createAopProxy(this);
	}

	public AopProxyFactory getAopProxyFactory() {
		return this.aopProxyFactory;
	}

createAopProxy的逻辑:

image-20221114175846276

1、当proxyTargetClass为true时,目标bean实现了接口或只有实现类都采用Cglib做动态代理;

2、当proxyTargetClass为false时,目标bean若实现了接口则采用JDK内置代理模式, 若目标bean只有实现类,则采用Cglib类代理模式;

3、默认proxyTargetClass为false;

DefaultAopProxyFactory
@Override
	public AopProxy createAopProxy(AdvisedSupport config) throws AopConfigException {
  
		if (!NativeDetector.inNativeImage() &&
				(config.isOptimize() || config.isProxyTargetClass() || hasNoUserSuppliedProxyInterfaces(config))) { //1 
			Class<?> targetClass = config.getTargetClass();
			if (targetClass == null) { //2 
				throw new AopConfigException("TargetSource cannot determine target class: " +
						"Either an interface or a target is required for proxy creation.");
			} //2 
			if (targetClass.isInterface() || Proxy.isProxyClass(targetClass) || ClassUtils.isLambdaClass(targetClass)) { ///2 
				return new JdkDynamicAopProxy(config);
			} //2
			return new ObjenesisCglibAopProxy(config);
		} //1
  
		else { //1 
			return new JdkDynamicAopProxy(config);
		}//1 
	}
TAG2.4.2 getProxy
TAG2.4.2.1 JdkDynamicAopProxy
	//构造函数
	public JdkDynamicAopProxy(AdvisedSupport config) throws AopConfigException {
		Assert.notNull(config, "AdvisedSupport must not be null");
		if (config.getAdvisorCount() == 0 && config.getTargetSource() == AdvisedSupport.EMPTY_TARGET_SOURCE) {
			throw new AopConfigException("No advisors and no TargetSource specified");
		}
		this.advised = config;
		this.proxiedInterfaces = AopProxyUtils.completeProxiedInterfaces(this.advised, true);
		findDefinedEqualsAndHashCodeMethods(this.proxiedInterfaces);
	}
	
	@Override
	public Object getProxy(@Nullable ClassLoader classLoader) {
		if (logger.isTraceEnabled()) {
			logger.trace("Creating JDK dynamic proxy: " + this.advised.getTargetSource());
		}
		//调用jdk代理创建
		return Proxy.newProxyInstance(classLoader, this.proxiedInterfaces, this);
	}
TAG2.4.2.2 ObjenesisCglibAopProxy
public ObjenesisCglibAopProxy(AdvisedSupport config) {
		super(config);
	}
	
	@Override
	protected Object createProxyClassAndInstance(Enhancer enhancer, Callback[] callbacks) {
    //cglib的enhancer配置类
		Class<?> proxyClass = enhancer.createClass();
		Object proxyInstance = null;

		if (objenesis.isWorthTrying()) {
			try {
				proxyInstance = objenesis.newInstance(proxyClass, enhancer.getUseCache());
			}
			catch (Throwable ex) {
				logger.debug("Unable to instantiate proxy using Objenesis, " +
						"falling back to regular proxy construction", ex);
			}
		}

		if (proxyInstance == null) {
			// Regular instantiation via default constructor...
			try {
				Constructor<?> ctor = (this.constructorArgs != null ?
						proxyClass.getDeclaredConstructor(this.constructorArgTypes) :
						proxyClass.getDeclaredConstructor());
				ReflectionUtils.makeAccessible(ctor);
				proxyInstance = (this.constructorArgs != null ?
						ctor.newInstance(this.constructorArgs) : ctor.newInstance());
			}
			catch (Throwable ex) {
				throw new AopConfigException("Unable to instantiate proxy using Objenesis, " +
						"and regular proxy instantiation via default constructor fails as well", ex);
			}
		}

		((Factory) proxyInstance).setCallbacks(callbacks);
		return proxyInstance;
	}
posted @ 2023-03-10 17:16  LeasonXue  阅读(54)  评论(0编辑  收藏  举报