spring-aop源码(一)创建AnnotationAwareAspectJAutoProxyCreator过程

系列文章目录

【spring-aop源码(一)创建AnnotationAwareAspectJAutoProxyCreator过程】

【spring-aop源码(二)创建代理对象过程】

【spring-aop源码(三)调用aop代理方法过程】

SpringBoot源码地址:https://github.com/spring-projects

SpringBoot版本:2.4.0-SNAPSHOT

SpringBoot分支:master


 

文章目录

前言

一、@EnableAspectJAutoProxy

二、创建AnnotationAwareAspectJAutoProxyCreator

总结


前言

在spring中,可以使用开启基于注解版的切面功能,自动为spring容器中那些配置了@AspectJ的切面配置类创建代理,然后在配置类中使用@EnableAspectJAutoProxy开启aop自动配置。

使用springboot可以直接为@AspectJ的切面配置类创建代理,而不需要其他的配置。因为从springboot官方文档中可以发现,springboot默认开启基于注解版的切面功能并且开启Cglib动态代理(具体原因可以看看这个类AopAutoConfiguration),spring官方文档相关配置截图如下。

从上图看出spring.aop.auto属性会添加@EnableAspectJAutoProxy,所以归根结底还是@EnableAspectJAutoProxy,下面对@EnableAspectJAutoProxy进行分析。


一、@EnableAspectJAutoProxy

@EnableAspectJAutoProxy源码如下。


package org.springframework.context.annotation;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Import({AspectJAutoProxyRegistrar.class})
public @interface EnableAspectJAutoProxy {
    boolean proxyTargetClass() default false;

    boolean exposeProxy() default false;
}

可以看到@EnableAspectJAutoProxy有两个属性:proxyTargetClass和exposeProxy,其默认值都是false(springboot默认是true)。proxyTargetClass属性、exposeProxy属性。@EnableAspectJAutoProxy为容器中Import AspectJAutoProxyRegistrar.class,其代码如下。

package org.springframework.context.annotation;

import org.springframework.aop.config.AopConfigUtils;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.core.annotation.AnnotationAttributes;
import org.springframework.core.type.AnnotationMetadata;

class AspectJAutoProxyRegistrar implements ImportBeanDefinitionRegistrar {

	@Override
	public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
		AopConfigUtils.registerAspectJAnnotationAutoProxyCreatorIfNecessary(registry);
		AnnotationAttributes enableAspectJAutoProxy =AnnotationConfigUtils.attributesFor(importingClassMetadata, EnableAspectJAutoProxy.class);
		if (enableAspectJAutoProxy != null) {
			if (enableAspectJAutoProxy.getBoolean("proxyTargetClass")) {
				AopConfigUtils.forceAutoProxyCreatorToUseClassProxying(registry);
			}
			if (enableAspectJAutoProxy.getBoolean("exposeProxy")) {
				AopConfigUtils.forceAutoProxyCreatorToExposeProxy(registry);
			}
		}
	}
}

其主要功能是通过AopConfigUtils向容器中注册BeanDefinition。继续跟进可以发现,该流程在必要的时候向容器中注册了AnnotationAwareAspectJAutoProxyCreator。AopConfigUtils中的注册方法如下。

	@Nullable
	public static BeanDefinition registerAspectJAnnotationAutoProxyCreatorIfNecessary(
			BeanDefinitionRegistry registry, @Nullable Object source) {
		return registerOrEscalateApcAsRequired(AnnotationAwareAspectJAutoProxyCreator.class, registry, source);
	}

 

 


二、创建AnnotationAwareAspectJAutoProxyCreator

问:为什么要创建AnnotationAwareAspectJAutoProxyCreator?

答:AnnotationAwareAspectJAutoProxyCreator中的findCandidateAdvisors()方法可以构建所有增强器,其代码如下。

@Override
	protected List findCandidateAdvisors() {
		// Add all the Spring advisors found according to superclass rules.
		List advisors = super.findCandidateAdvisors();
		// Build Advisors for all AspectJ aspects in the bean factory.
		if (this.aspectJAdvisorsBuilder != null) {
			advisors.addAll(this.aspectJAdvisorsBuilder.buildAspectJAdvisors());
		}
		return advisors;
	}

下面分析AnnotationAwareAspectJAutoProxyCreator的创建过程,顺便熟悉springboot启动过程。

调用过程:SpringApplication.run(Class primarySource, String... args)

->SpringApplication.run(Class[] primarySources, String[] args)

->SpringApplication.run(String... args)(①)

->SpringApplication.refreshContext(ConfigurableApplicationContext context)

->SpringApplication.refresh(ApplicationContext applicationContext)

->SpringApplication.refresh(ConfigurableApplicationContext applicationContext)

->AbstractApplicationContext.refresh()

->AbstractApplicationContext.registerBeanPostProcessors(ConfigurableListableBeanFactory beanFactory)

->PostProcessorRegistrationDelegate.registerBeanPostProcessors(ConfigurableListableBeanFactory beanFactory, AbstractApplicationContext applicationContext)(②)

->AbstractBeanFactory.getBean(String name, Class requiredType)

->AbstractBeanFactory.doGetBean(String name, @Nullable Class requiredType, @Nullable Object[] args, boolean typeCheckOnly)

->DefaultSingletonBeanRegistry.getSingleton(String beanName, ObjectFactory singletonFactory)

->AbstractAutowireCapableBeanFactory.createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)

->AbstractAutowireCapableBeanFactory.doCreateBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)(③)

其中可以将紫色部分由springboot完成,蓝色部分由spring完成。下面着重分析上面的(①)(②)(③)

① SpringApplication.run(String... args) 主要由springboot完成,其主要功能是运行Spring应用程序,创建并刷新一个新的ApplicationContext,步骤详情看注释。

public ConfigurableApplicationContext run(String... args) {
		//计时工具作为时间监控
		StopWatch stopWatch = new StopWatch();
		stopWatch.start();
		ConfigurableApplicationContext context = null;
		Collection exceptionReporters = new ArrayList<>();
		// Headless模式是系统的一种配置模式。在该模式下,系统缺少了显示设备、键盘或鼠标。
		// 设置java.awt.headless系统属性为true - 没有图形化界面
		configureHeadlessProperty();
		/**
		 * 获取SpringApplicationRunListeners
		 * getSpringFactoriesInstances方法,从META-INF/spring.factories中读取
		 * Key为org.springframework.boot.SpringApplicationRunListener的Values
		 * SpringApplicationEvent:它会利用一个内部的ApplicationEventMulticaster在上下文实际被刷新之前对事件进行处理
		 * 它实际上是一个事件中转器,它能够感知到Spring Boot启动过程中产生的事件,然后有选择性的将事件进行中转
		 */
		// 第一步:获取并启动监听器    Spring事件体系 https://blog.csdn.net/caihaijiang/article/details/7460888
		SpringApplicationRunListeners listeners = getRunListeners(args);
		// 发出开始执行的事件
		listeners.starting();
		try {
			ApplicationArguments applicationArguments = new DefaultApplicationArguments(args);
			// 第二步:构造容器环境    根据SpringApplicationRunListeners以及参数来准备环境
			ConfigurableEnvironment environment = prepareEnvironment(listeners, applicationArguments);
			// 设置需要忽略的bean
			configureIgnoreBeanInfo(environment);
			// 启动Spring Boot时在console上打印ASCII艺术字体
			Banner printedBanner = printBanner(environment);
			// 第三步:创建容器    创建Spring上下文,根据之前获得的应用类型,创建ConfigurableApplicationContext实例
			// 可以看到实际上创建的是AnnotationConfigApplicationContext或AnnotationConfigEmbeddedWebApplicationContext。
			context = createApplicationContext();
			// 设置启动方式:applicationStartup旨在最大程度地减少开销,并且不记录事件
			context.setApplicationStartup(this.applicationStartup);
			// 第四步:实例化SpringBootExceptionReporter.class,用来支持报告关于启动的错误    获取"META-INF/spring.factories"中的SpringBootExceptionReporter类并完成构造
			exceptionReporters = getSpringFactoriesInstances(SpringBootExceptionReporter.class,
					new Class[]{ConfigurableApplicationContext.class}, context);
			// Spring上下文前置处理,准备容器,prepareContext方法中将会执行每个initializers的逻辑
			// 第五步:准备容器,包含一个非常关键的操作:将启动类注入容器,为后续开启自动化配置奠定基础。
			prepareContext(context, environment, listeners, applicationArguments, printedBanner);
			// 第六步:刷新容器,Spring上下文刷新。  执行到这里,springBoot相关的处理工作已经结束,接下的工作就交给了spring。
			// refresh方法在spring整个源码体系中举足轻重,是实现 ioc 和 aop的关键。
			refreshContext(context);
			// 第七步:刷新容器后的扩展接口,Spring上下文后置处理。
			afterRefresh(context, applicationArguments);
			// 结束执行的事件
			stopWatch.stop();
			if (this.logStartupInfo) {
				new StartupInfoLogger(this.mainApplicationClass).logStarted(getApplicationLog(), stopWatch);
			}
			listeners.started(context);
            //执行实现了CommandLineRunner和ApplicationRunner的run方法
			callRunners(context, applicationArguments);
		} catch (Throwable ex) {
			handleRunFailure(context, ex, exceptionReporters, listeners);
			throw new IllegalStateException(ex);
		}
		try {
			listeners.running(context);
		} catch (Throwable ex) {
			handleRunFailure(context, ex, exceptionReporters, null);
			throw new IllegalStateException(ex);
		}
		return context;
	}

② PostProcessorRegistrationDelegate.registerBeanPostProcessors(ConfigurableListableBeanFactory beanFactory, AbstractApplicationContext applicationContext)

public static void registerBeanPostProcessors(ConfigurableListableBeanFactory beanFactory, AbstractApplicationContext applicationContext) {
		String[] postProcessorNames =beanFactory.getBeanNamesForType(BeanPostProcessor.class, true, false);
		// 注册BeanPostProcessorChecker用来在以下情况下记录信息消息:
		//在BeanPostProcessor实例化期间当一个bean不适合所有BeanPostProcessor处理。
		int beanProcessorTargetCount = beanFactory.getBeanPostProcessorCount() + 1 + postProcessorNames.length;
		beanFactory.addBeanPostProcessor(new BeanPostProcessorChecker(beanFactory, beanProcessorTargetCount));
		// Separate between BeanPostProcessors that implement PriorityOrdered,
		// Ordered, and the rest.
		List priorityOrderedPostProcessors = new ArrayList<>();
		List internalPostProcessors = new ArrayList<>();
		List orderedPostProcessorNames = new ArrayList<>();
		List nonOrderedPostProcessorNames = new ArrayList<>();
		for (String ppName : postProcessorNames) {
			if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
				BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
				priorityOrderedPostProcessors.add(pp);
				if (pp instanceof MergedBeanDefinitionPostProcessor) {
					internalPostProcessors.add(pp);
				}
			}
			else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
				orderedPostProcessorNames.add(ppName);
			}
			else {
				nonOrderedPostProcessorNames.add(ppName);
			}
		}
		// 首先,注册实现PriorityOrdered的BeanPostProcessor。
		sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
		registerBeanPostProcessors(beanFactory, priorityOrderedPostProcessors);
		// 接下来,注册实现Ordered的BeanPostProcessor。
		List orderedPostProcessors = new ArrayList<>(orderedPostProcessorNames.size());
		for (String ppName : orderedPostProcessorNames) {
			BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
			orderedPostProcessors.add(pp);
			if (pp instanceof MergedBeanDefinitionPostProcessor) {
				internalPostProcessors.add(pp);
			}
		}
		sortPostProcessors(orderedPostProcessors, beanFactory);
		registerBeanPostProcessors(beanFactory, orderedPostProcessors);
		// 注册所有常规BeanPostProcessor。
		List nonOrderedPostProcessors = new ArrayList<>(nonOrderedPostProcessorNames.size());
		for (String ppName : nonOrderedPostProcessorNames) {
			BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
			nonOrderedPostProcessors.add(pp);
			if (pp instanceof MergedBeanDefinitionPostProcessor) {
				internalPostProcessors.add(pp);
			}
		}
		registerBeanPostProcessors(beanFactory, nonOrderedPostProcessors);
		// 最后,重新注册所有内部BeanPostProcessor。
		sortPostProcessors(internalPostProcessors, beanFactory);
		registerBeanPostProcessors(beanFactory, internalPostProcessors);
		// 重新注册用于将内部bean检测为ApplicationListener的后处理器。
		// 将其移动到处理器链的末尾(用于拾取代理等)。
		beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(applicationContext));
	}

③ AbstractAutowireCapableBeanFactory.doCreateBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)

protected Object doCreateBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)throws BeanCreationException {
		//实例化bean。从名字可以看出,这个类用来包装Bean
		BeanWrapper instanceWrapper = null;
		if (mbd.isSingleton()) {
			instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
		}
		if (instanceWrapper == null) {
        //创建实例
            //a. Class beanClass = resolveBeanClass(mbd, beanName);获取bean的类,可以在获取的beanClass中看到name为实际创建的AnnotationAwareAspectJAutoProxyCreator(终于露出了庐山真面目)
	        //b. 可以看到实例化有两种方式:构造函数自动装配或简单实例化
            //c. return instantiateBean(beanName, mbd);最终可以看到,该bean无需特殊处理,使用no-arg构造函数即可
			instanceWrapper = createBeanInstance(beanName, mbd, args);
		}
		Object bean = instanceWrapper.getWrappedInstance();
		Class beanType = instanceWrapper.getWrappedClass();
		if (beanType != NullBean.class) {
			mbd.resolvedTargetType = beanType;
		}
		// 允许后处理器修改合并的bean定义。
		synchronized (mbd.postProcessingLock) {
			if (!mbd.postProcessed) {
				try {
					applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
				}
				catch (Throwable ex) {
					throw new BeanCreationException(mbd.getResourceDescription(), beanName,
							"Post-processing of merged bean definition failed", ex);
				}
				mbd.postProcessed = true;
			}
		}
		// 该实例是一个需要急切缓存的单例,这种实例可以在生命周期接口触发时也能够解析循环引用
		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");
			}
			addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
		}
		// 初始化bean实例。
		Object exposedObject = bean;
		try {
            //这里就是给bean的各种属性赋值
                	// a. PropertyValues pvs = (mbd.hasPropertyValues() ? mbd.getPropertyValues() : null);获取bean的属性值
	                // b. applyPropertyValues(beanName, mbd, bw, pvs);应用各种属性值
			populateBean(beanName, mbd, instanceWrapper);
            //初始化bean
                // a. invokeAwareMethods(beanName, bean);处理Aware接口的方法回调(??)
	            // b. applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);应用后置处理器的postProcessBeforeInitialization()
	            // c. invokeInitMethods(beanName, wrappedBean, mbd); 执行自定义的初始化方法
	            // d. applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);执行后置处理器的postProcessAfterInitialization()
			exposedObject = initializeBean(beanName, exposedObject, mbd);
		}
		catch (Throwable ex) {
			if (ex instanceof BeanCreationException && beanName.equals(((BeanCreationException) ex).getBeanName())) {
				throw (BeanCreationException) ex;
			}
			else {
				throw new BeanCreationException(
						mbd.getResourceDescription(), beanName, "Initialization of bean failed", ex);
			}
		}
		if (earlySingletonExposure) {
			Object earlySingletonReference = getSingleton(beanName, false);
			if (earlySingletonReference != null) {
				if (exposedObject == bean) {
					exposedObject = earlySingletonReference;
				}
				else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) {
					String[] dependentBeans = getDependentBeans(beanName);
					Set actualDependentBeans = new LinkedHashSet<>(dependentBeans.length);
					for (String dependentBean : dependentBeans) {
						if (!removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) {
							actualDependentBeans.add(dependentBean);
						}
					}
					if (!actualDependentBeans.isEmpty()) {
						throw new BeanCurrentlyInCreationException(beanName,
								"Bean with name '" + beanName + "' has been injected into other beans [" +
								StringUtils.collectionToCommaDelimitedString(actualDependentBeans) +
								"] in its raw version as part of a circular reference, but has eventually been " +
								"wrapped. This means that said other beans do not use the final version of the " +
								"bean. This is often the result of over-eager type matching - consider using " +
								"'getBeanNamesForType' with the 'allowEagerInit' flag turned off, for example.");
					}
				}
			}
		}
		// 将bean注册为一次性的。
		try {
			registerDisposableBeanIfNecessary(beanName, bean, mbd);
		}
		catch (BeanDefinitionValidationException ex) {
			throw new BeanCreationException(
					mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex);
		}
		return exposedObject;
	}

创建AnnotationAwareAspectJAutoProxyCreator调试过程下图所示。实际创建:internalAutoProxyCreator->AnnotationAwareAspectJAutoProxyCreator

spring-aop源码(一)创建AnnotationAwareAspectJAutoProxyCreator过程_第1张图片

最终在容器中创建了AnnotationAwareAspectJAutoProxyCreator,那么AnnotationAwareAspectJAutoProxyCreator到底有些什么方法呢?其源码如下。主要功能是在创建目标代理类的过程中,根据条件给目标代理类包装相应的增强器,以便生成增强后的代理类。

package org.springframework.aop.aspectj.annotation;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
import org.springframework.aop.Advisor;
import org.springframework.aop.aspectj.autoproxy.AspectJAwareAdvisorAutoProxyCreator;
import org.springframework.beans.factory.ListableBeanFactory;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
/**
 *其所有子类,用于处理当前应用程序上下文中的所有@AspectJ的切面以及Spring Advisor。
**/
@SuppressWarnings("serial")
public class AnnotationAwareAspectJAutoProxyCreator extends AspectJAwareAdvisorAutoProxyCreator {

	@Nullable
	private List includePatterns;

	@Nullable
	private AspectJAdvisorFactory aspectJAdvisorFactory;

	@Nullable
	private BeanFactoryAspectJAdvisorsBuilder aspectJAdvisorsBuilder;


	/**
	 * 设置一个正则表达式模式列表,匹配合格的@AspectJ bean名称。
	 * 默认是将所有@AspectJ bean视为合格
	 */
	public void setIncludePatterns(List patterns) {
		this.includePatterns = new ArrayList<>(patterns.size());
		for (String patternText : patterns) {
			this.includePatterns.add(Pattern.compile(patternText));
		}
	}

	public void setAspectJAdvisorFactory(AspectJAdvisorFactory aspectJAdvisorFactory) {
		Assert.notNull(aspectJAdvisorFactory, "AspectJAdvisorFactory must not be null");
		this.aspectJAdvisorFactory = aspectJAdvisorFactory;
	}
    //初始化bean工厂
	@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);
	}
    //获取所有增强器
	@Override
	protected List findCandidateAdvisors() {
		// Add all the Spring advisors found according to superclass rules.
		List advisors = super.findCandidateAdvisors();
		// Build Advisors for all AspectJ aspects in the bean factory.
		if (this.aspectJAdvisorsBuilder != null) {
			advisors.addAll(this.aspectJAdvisorsBuilder.buildAspectJAdvisors());
		}
		return advisors;
	}

	@Override
	protected boolean isInfrastructureClass(Class beanClass) {
		return (super.isInfrastructureClass(beanClass) ||
				(this.aspectJAdvisorFactory != null && this.aspectJAdvisorFactory.isAspect(beanClass)));
	}

	/**
	 * 检查给定的切面bean是否符合自动代理的条件。
	 */
	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;
		}
	}

	/**
	 *BeanFactoryAspectJAdvisorsBuilderAdapter的子类,委托给周围的AnnotationAwareAspectJAutoProxyCreator工具。
	 */
	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);
		}
	}
}

 


总结

关键词:spring-aop、AnnotationAwareAspectJAutoProxyCreator创建过程、AnnotationAwareAspectJAutoProxyCreator作用

你可能感兴趣的:(Spring)