SpringAOP源码解析(AnnotationAwareAspectJAutoProxyCreator 注册)

下面的源码分析基于Spring版本 5.0.6.RELEASE

目录

分析创建和注册AnnotationAwareAspectJAutoProxyCreator的流程

1、瞧瞧这个注解都有啥

2、接下来重点研究 AnnotationAwareAspectJAutoProxyCreator的创建过程

3、我们来展开分析一下做为beanPostProcessor后置处理器,究竟做了哪些工作;做为BeanFactoryAware又做了哪些工作:

3.1、register()传入配置类,准备创建ioc容器

3.2、调用refresh()刷新创建容器;

3.3、分析方法 registerBeanPostProcessors(beanFactory) ;

3.3.1、创建 internalAutoProxyCreatorr

3.3.2、初始化实例 internalAutoProxyCreator

3.3.3、注册实现了Ordered接口的BeanPostProcessor;


分析创建和注册AnnotationAwareAspectJAutoProxyCreator的流程

AnnotationAwareAspectJAutoProxyCreator 翻译过来其实就叫做 ”注解装配模式的ASPECT切面自动代理创建器”组件@EnableAspectJAutoProxy 核心从这个入手,AOP整个功能要启作用,就靠这个注解

1、瞧瞧这个注解都有啥

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
// 关注这个引入的类,这是整个AOP的入口
@Import(AspectJAutoProxyRegistrar.class)
public @interface EnableAspectJAutoProxy {

	/**
	 * 采用JDK动态代理织入增强(实现接口的方式);如果设为true,则采用CGLIB动态代理织入增强
	 */
	boolean proxyTargetClass() default false;

	/**
	 * 通过aop框架暴露该代理对象,让aopContext能够访问
	 */
	boolean exposeProxy() default false;

}

当 AbstractApplicationContext 执行 refresh()方法时,在 invokeBeanFactoryPostProcessors(beanFactory) 方法执行时会回调所有实现了接口 ImportBeanDefinitionRegistrar 的 registerBeanDefinitions 方法 

class AspectJAutoProxyRegistrar implements ImportBeanDefinitionRegistrar {
	@Override
	public void registerBeanDefinitions(
			AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
                // 注册组件 AnnotationAwareAspectJAutoProxyCreator.class,关注这行
		AopConfigUtils.registerAspectJAnnotationAutoProxyCreatorIfNecessary(registry);

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

 

// org.springframework.aop.config.AopConfigUtils.java line 103 ,注册组件	
public static BeanDefinition registerAspectJAnnotationAutoProxyCreatorIfNecessary(BeanDefinitionRegistry registry,
			@Nullable Object source) {
		return 
// 注册或升级 AnnotationAwareAspectJAutoProxyCreator.class,第一次我们只关注注册
registerOrEscalateApcAsRequired(AnnotationAwareAspectJAutoProxyCreator.class, registry, source);
	}

 跟进代码看看,这里会注册一个名为  org.springframework.aop.config.internalAutoProxyCreator  的组件

	private static BeanDefinition registerOrEscalateApcAsRequired(Class cls, BeanDefinitionRegistry registry,
			@Nullable Object source) {
		Assert.notNull(registry, "BeanDefinitionRegistry must not be null");
		if (registry.containsBeanDefinition(AUTO_PROXY_CREATOR_BEAN_NAME)) {
			BeanDefinition apcDefinition = registry.getBeanDefinition(AUTO_PROXY_CREATOR_BEAN_NAME);
			if (!cls.getName().equals(apcDefinition.getBeanClassName())) {
				int currentPriority = findPriorityForClass(apcDefinition.getBeanClassName());
				int requiredPriority = findPriorityForClass(cls);
				if (currentPriority < requiredPriority) {
					apcDefinition.setBeanClassName(cls.getName());
				}
			}
			return null;
		}
		RootBeanDefinition beanDefinition = new RootBeanDefinition(cls);
		beanDefinition.setSource(source);
		beanDefinition.getPropertyValues().add("order", Ordered.HIGHEST_PRECEDENCE);
		beanDefinition.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
                // 真正注册组件的地方,该常量名为:org.springframework.aop.config.internalAutoProxyCreator
		registry.registerBeanDefinition(AUTO_PROXY_CREATOR_BEAN_NAME, beanDefinition);
		return beanDefinition;
	}

2、接下来重点研究 AnnotationAwareAspectJAutoProxyCreator的创建过程

先来一张类继承关系图

SpringAOP源码解析(AnnotationAwareAspectJAutoProxyCreator 注册)_第1张图片 标题

SmartInstantiationAwareBeanPostProcessor: bean的后置处理器;
BeanFactoryAware 能把beanFacotry bean工厂传进来 ;
通过分析以上的bean继承关系我们发现,具有BeanPostProcessor特点, 也有Aware接口的特点, 实现了BeanFactoryAware 接口;

3、我们来展开分析一下做为beanPostProcessor后置处理器,究竟做了哪些工作;做为BeanFactoryAware又做了哪些工作:

3.1、register()传入配置类,准备创建ioc容器

//	org.springframework.context.annotation.AnnotationConfigApplicationContext line 87
public AnnotationConfigApplicationContext(Class... annotatedClasses) {
		this();
                // 注册配置类,跟进去看
		register(annotatedClasses);
		refresh();
	}
//	org.springframework.context.annotation.AnnotatedBeanDefinitionReader line 213
 void doRegisterBean(Class annotatedClass, @Nullable Supplier instanceSupplier, @Nullable String name,
			@Nullable Class[] qualifiers, BeanDefinitionCustomizer... definitionCustomizers) {
		AnnotatedGenericBeanDefinition abd = new AnnotatedGenericBeanDefinition(annotatedClass);
		if (this.conditionEvaluator.shouldSkip(abd.getMetadata())) {
			return;
		}
		abd.setInstanceSupplier(instanceSupplier);
		ScopeMetadata scopeMetadata = this.scopeMetadataResolver.resolveScopeMetadata(abd);
		abd.setScope(scopeMetadata.getScopeName());
		String beanName = (name != null ? name : this.beanNameGenerator.generateBeanName(abd, this.registry));
		AnnotationConfigUtils.processCommonDefinitionAnnotations(abd);
		if (qualifiers != null) {
			for (Class qualifier : qualifiers) {
				if (Primary.class == qualifier) {
					abd.setPrimary(true);
				}
				else if (Lazy.class == qualifier) {
					abd.setLazyInit(true);
				}
				else {
					abd.addQualifier(new AutowireCandidateQualifier(qualifier));
				}
			}
		}
		for (BeanDefinitionCustomizer customizer : definitionCustomizers) {
			customizer.customize(abd);
		}
		BeanDefinitionHolder definitionHolder = new BeanDefinitionHolder(abd, beanName);
		definitionHolder = AnnotationConfigUtils.applyScopedProxyMode(scopeMetadata, definitionHolder, this.registry);
                // 注册BeanDefinition
		BeanDefinitionReaderUtils.registerBeanDefinition(definitionHolder, this.registry);
	}

3.2、调用refresh()刷新创建容器;

//	org.springframework.context.annotation.AnnotationConfigApplicationContext line 88	
public AnnotationConfigApplicationContext(Class... annotatedClasses) {
		this();
		register(annotatedClasses);
                // 刷新创建容器
		refresh();
	}
	public void refresh() throws BeansException, IllegalStateException {
		// 来个锁,不然 refresh() 还没结束,你又来个启动或销毁容器的操作,那不就乱套了嘛
		synchronized (this.startupShutdownMonitor) {
			// 准备工作,记录下容器的启动时间、标记“已启动”状态、处理配置文件中的占位符
			prepareRefresh();
			// ☆☆,这步完成后,配置文件就会解析成一个个 Bean 定义,注册到 BeanFactory 中,
      		        // 当然,这里说的 Bean 还没有初始化,只是配置信息都提取出来了,
      		        // 注册也只是将这些信息都保存到了ioc容器中
			ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
			// 设置 BeanFactory 的类加载器,添加几个 BeanPostProcessor,手动注册几个特殊的 bean
			prepareBeanFactory(beanFactory);
			try {
         		        // 这里是提供给子类的扩展点,到这里的时候,所有的 Bean 都加载、注册完成了,但是都还没有初始化
         		        // 具体的子类可以在这步的时候添加一些特殊的 BeanFactoryPostProcessor 的实现类或做点什么事
				postProcessBeanFactory(beanFactory);
				// 调用 BeanFactoryPostProcessor 各个实现类的 postProcessBeanFactory(factory) 方法
				invokeBeanFactoryPostProcessors(beanFactory);
				    // 注册 BeanPostProcessor 的实现类,注意看和 BeanFactoryPostProcessor 的区别
         		        // BeanPostProcessor接口有两个方法: postProcessBeforeInitialization 和 postProcessAfterInitialization
         		        // 而BeanFactoryPostProcessor接口只有一个方法:postProcessBeanFactory
         		        // 两个方法分别在 Bean 初始化之前和初始化之后得到执行。注意,到这里 Bean 还没初始化
				registerBeanPostProcessors(beanFactory);
				// 初始化当前 ApplicationContext 的 MessageSource,国际化相关代码略过不谈
				initMessageSource();
				// 初始化当前 ApplicationContext 的事件广播器,这里也不展开了
				initApplicationEventMulticaster();
				// 典型的模板方法,具体的子类可以在这里初始化一些特殊的 Bean(在初始化 singleton beans 之前)
				onRefresh();
				// 注册事件监听器,监听器需要实现 ApplicationListener 接口。这也不是我们的重点,过
				registerListeners();
				// ★★★★,初始化所有的 singleton beans,lazy-init 的除外,圈起来,重点必考题
				finishBeanFactoryInitialization(beanFactory);
				// 最后,广播事件,ApplicationContext 初始化完成
				finishRefresh();
			}
			catch (BeansException ex) {
				if (logger.isWarnEnabled()) {
					logger.warn("Exception encountered during context initialization - " +
							"cancelling refresh attempt: " + ex);
				}
				// 销毁已经初始化的 singleton 的 Beans,以免有些 bean 会一直占用资源
				destroyBeans();
				// Reset 'active' flag.
				cancelRefresh(ex);
				// Propagate exception to caller.
				throw ex;
			}
			finally {
				// Reset common introspection caches in Spring's core, since we
				// might not ever need metadata for singleton beans anymore...
				resetCommonCaches();
			}
		}
	}

3.3、分析方法 registerBeanPostProcessors(beanFactory) ;

注册bean的后置处理器,用来拦截其他bean的创建(主要关注在哪里注册AnnotationAwareAspectJAutoProxyCreator);

	protected void registerBeanPostProcessors(ConfigurableListableBeanFactory beanFactory) {
		PostProcessorRegistrationDelegate.registerBeanPostProcessors(beanFactory, this);
	}

  •      先获取ioc容器已经定义了的需要创建对象的所有BeanPostProcessor
  •      给容器中加别的BeanPostProcessor
  •      优先注册实现了PriorityOrdered接口的BeanPostProcessor;
  •      创建后置处理器 internalAutoProxyCreator

  •      注册实现了Ordered接口的BeanPostProcessor;
  •      注册没实现优先级接口的BeanPostProcessor;
  •      最后注册Spring内部的BeanPostProcessor;
// org.springframework.context.support.PostProcessorRegistrationDelegate line 186
public static void registerBeanPostProcessors(
			ConfigurableListableBeanFactory beanFactory, AbstractApplicationContext applicationContext) {
		// 1)、 先获取ioc容器已经定义了的需要创建对象的所有BeanPostProcessor
		String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanPostProcessor.class, true, false);
		int beanProcessorTargetCount = beanFactory.getBeanPostProcessorCount() + 1 + postProcessorNames.length;
		// 2)、给容器中加额外的BeanPostProcessor
		beanFactory.addBeanPostProcessor(new BeanPostProcessorChecker(beanFactory, beanProcessorTargetCount));
		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);
			}
		}
		sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
		// 3)、优先注册实现了PriorityOrdered接口的BeanPostProcessor;
		registerBeanPostProcessors(beanFactory, priorityOrderedPostProcessors);
		List orderedPostProcessors = new ArrayList<>();
		for (String ppName : orderedPostProcessorNames) {
                        // 4)、☆☆☆ 创建后置处理器 internalAutoProxyCreator,下文会单独讲解
			BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
			orderedPostProcessors.add(pp);
			if (pp instanceof MergedBeanDefinitionPostProcessor) {
				internalPostProcessors.add(pp);
			}
		}
		sortPostProcessors(orderedPostProcessors, beanFactory);
		/* 5)、☆再给容器中注册实现了Ordered接口的BeanPostProcessor,其中 AnnotationAwareAspectJAutoProxyCreator 就是在这里进行注册的*/
		registerBeanPostProcessors(beanFactory, orderedPostProcessors);
		List nonOrderedPostProcessors = new ArrayList<>();
		for (String ppName : nonOrderedPostProcessorNames) {
			BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
			nonOrderedPostProcessors.add(pp);
			if (pp instanceof MergedBeanDefinitionPostProcessor) {
				internalPostProcessors.add(pp);
			}
		}
		// 6)、注册没实现优先级接口的BeanPostProcessor;
		registerBeanPostProcessors(beanFactory, nonOrderedPostProcessors);
		sortPostProcessors(internalPostProcessors, beanFactory);
		// 7)、注册Spring已经创建好的BeanPostProcessor;
		registerBeanPostProcessors(beanFactory, internalPostProcessors);
		beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(applicationContext));
	}

接下来分三个步骤讲解,分别是创建实例,初始化实例,初始化包含(应用工厂回调以及init方法和bean后处理器);这两个小步骤是上文中的 创建后置处理器 internalAutoProxyCreator  的拆分;然后讲解  注册实现了Ordered接口的BeanPostProcessor; 

3.3.1、创建 internalAutoProxyCreatorr

【其实就是AnnotationAwareAspectJAutoProxyCreator】,代码跟到上述代码中提到的第4)点,对应代码 

BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);跟进去瞅瞅;

// org.springframework.beans.factory.support.AbstractBeanFactory line 239
protected  T doGetBean(final String name, @Nullable final Class requiredType,
			@Nullable final Object[] args, boolean typeCheckOnly) throws BeansException {
		final String beanName = transformedBeanName(name);
		Object bean;
		// 容器此时还没有该Bean,返回 null
		Object sharedInstance = getSingleton(beanName);
		// 此处忽略部分代码 ···
				if (mbd.isSingleton()) {
					sharedInstance = getSingleton(beanName, () -> {
						try {
							// 调用父类的父类的方法创建bean
							return createBean(beanName, mbd, args);
						}
						catch (BeansException ex) {
							destroySingleton(beanName);
							throw ex;
						}
					});
					bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
				}
		// 此处忽略部分代码 ···
		}

这里看一下Bean工厂的继承关系,当前Bean工厂为 强悍的DefaultListableBeanFactory,向上转型成  AbstractBeanFactory,执行AbstractBeanFactory的方法 createBean(beanName, mbd, args),该方法是在其父类的父类 DefaultSingletonBeanRegistry 中定义的,被其子类 AbstractAutowireCapableBeanFactory 重写,所以下面关注 AbstractAutowireCapableBeanFactory 这个类;

SpringAOP源码解析(AnnotationAwareAspectJAutoProxyCreator 注册)_第2张图片

我们看看类 AbstractAutowireCapableBeanFactory  方法

createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)

	// org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.java line 501
	protected Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
			throws BeanCreationException {
		if (logger.isDebugEnabled()) {
			logger.debug("Creating instance of bean '" + beanName + "'");
		}
		RootBeanDefinition mbdToUse = mbd;
		// 解析bean的类型
		Class resolvedClass = resolveBeanClass(mbd, beanName);
		if (resolvedClass != null && !mbd.hasBeanClass() && mbd.getBeanClassName() != null) {
			mbdToUse = new RootBeanDefinition(mbd);
			mbdToUse.setBeanClass(resolvedClass);
		}
		// 处理override method方法
		try {
			mbdToUse.prepareMethodOverrides();
		}
		catch (BeanDefinitionValidationException ex) {
			throw new BeanDefinitionStoreException(mbdToUse.getResourceDescription(),
					beanName, "Validation of method overrides failed", ex);
		}
		try {
			// 返回代理对象,AOP的实现基础就是基于这里来实现的,后续讲被切面拦截的对象创建时会详细讲解,这里暂时略过
			Object bean = resolveBeforeInstantiation(beanName, mbdToUse);
			if (bean != null) {
				return bean;
			}
		}
		catch (Throwable ex) {
			throw new BeanCreationException(mbdToUse.getResourceDescription(), beanName,
					"BeanPostProcessor before instantiation of bean failed", ex);
		}
		try {
			// ☆☆☆☆ 创建对象,此时beanName = "org.springframework.aop.config.internalAutoProxyCreator",args = null;
			Object beanInstance = doCreateBean(beanName, mbdToUse, args);
			if (logger.isDebugEnabled()) {
				logger.debug("Finished creating instance of bean '" + beanName + "'");
			}
			return beanInstance;
		}
		// catch 部分代码省略···
	}

	// org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.java line 532
	protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final @Nullable Object[] args)
			throws BeanCreationException {
		// bean实例包装类,用于操作bean的属性		
		BeanWrapper instanceWrapper = null;
		// 如果是单例的话,则先把工厂bean缓存中的同名bean清除
		if (mbd.isSingleton()) {
			instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
		}
		if (instanceWrapper == null) {
			// ☆☆ 创建bean实例,下面的代码会讲解,看看注释了解即可。
			instanceWrapper = createBeanInstance(beanName, mbd, args);
		}
		final Object bean = instanceWrapper.getWrappedInstance();
		// 获取BeanWrapper中封装的bean的Class
		Class beanType = instanceWrapper.getWrappedClass();
		if (beanType != NullBean.class) {
			mbd.resolvedTargetType = beanType;
		}
		synchronized (mbd.postProcessingLock) {
			if (!mbd.postProcessed) {
				try {
					 // bean 的生命周期之一。如果实现了MergedBeanDefinitionPostProcessor会在这里调用postProcessMergedBeanDefinition方法
					applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
				}
				catch (Throwable ex) {
					throw new BeanCreationException(mbd.getResourceDescription(), beanName,
							"Post-processing of merged bean definition failed", ex);
				}
				mbd.postProcessed = true;
			}
		}
		// 如果RootBeanDefinition是单例的,并且开启了自动尝试解析bean之间的循环引用,并且当前bean正在创建中,则将其加入单例工厂缓存singletonFactories中,是个Map>
		boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences &&
				isSingletonCurrentlyInCreation(beanName));
		if (earlySingletonExposure) {
			if (logger.isDebugEnabled()) {
				logger.debug("Eagerly caching bean '" + beanName +
						"' to allow for resolving potential circular references");
			}
			/* 将 org.springframework.aop.config.internalAutoProxyCreator 加入单例工厂缓存singletonFactories,以下截取了主要代码进行展示			
				this.singletonFactories.put(beanName, singletonFactory);
				this.earlySingletonObjects.remove(beanName);
				this.registeredSingletons.add(beanName);
			 */
			addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
		}
		// 对已有的bean的实例初始化  一般情况下依赖注入就在这里发生
		Object exposedObject = bean;
		try {
			// 填充bean的属性
			populateBean(beanName, mbd, instanceWrapper);
			// ☆☆☆ 初始化bean的实例,应用工厂回调以及init方法和bean后处理器
			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) {
			// 从BeanFactory的单例缓存中获取bean的实例
			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 部分代码省略···
					}
				}
			}
		}
		// 注册bean的销毁逻辑
		try {
			registerDisposableBeanIfNecessary(beanName, bean, mbd);
		}
		catch (BeanDefinitionValidationException ex) {
			throw new BeanCreationException(
					mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex);
		}
		return exposedObject;
	}	

接着上述代码中的 带有注释【☆☆ 创建bean实例】的行,简单讲解下

		// org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.java line 1135
		protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) {
			// 此处 beanClass = org.springframework.aop.aspectj.annotation.AnnotationAwareAspectJAutoProxyCreator
			Class beanClass = resolveBeanClass(mbd, beanName);
			// 中间省略大量代码,最终会执行到这行,即使用无参构造函数创建Bean
			return instantiateBean(beanName, mbd);
		}	
			// org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.java line 1228
			protected BeanWrapper instantiateBean(final String beanName, final RootBeanDefinition mbd) {
			try {
				Object beanInstance;
				final BeanFactory parent = this;
				if (System.getSecurityManager() != null) {
					beanInstance = AccessController.doPrivileged((PrivilegedAction) () ->
							getInstantiationStrategy().instantiate(mbd, beanName, parent),
							getAccessControlContext());
				}
				else {
					// 实例化bean,跟上节奏,别掉队
					beanInstance = getInstantiationStrategy().instantiate(mbd, beanName, parent);
				}
				// 将实例化的 bean 进行包装
				BeanWrapper bw = new BeanWrapperImpl(beanInstance);
				initBeanWrapper(bw);
				return bw;
			}
			// catch 部分代码省略···
			}
				// 此时代码跳转到了 org.springframework.beans.factory.support.SimpleInstantiationStrategy.java line 61
				public Object instantiate(RootBeanDefinition bd, @Nullable String beanName, BeanFactory owner) {
				if (!bd.hasMethodOverrides()) {
					Constructor constructorToUse;
					// 省略部分代码 ···
					// 使用 springframework 内部工具类创建实例,跟进去看看
					return BeanUtils.instantiateClass(constructorToUse);
				}
				else {
					return instantiateWithMethodInjection(bd, beanName, owner);
				}
				}
					// org.springframework.beans.BeanUtils line 170
					public static  T instantiateClass(Constructor ctor, Object... args) throws BeanInstantiationException {
						Assert.notNull(ctor, "Constructor must not be null");
						try {
							ReflectionUtils.makeAccessible(ctor);
							// 跟进 ctor.newInstance(args)
							return (KotlinDetector.isKotlinType(ctor.getDeclaringClass()) ?
									KotlinDelegate.instantiateClass(ctor, args) : ctor.newInstance(args));
						}
						// catch 异常部分代码略
					}
						// java.lang.reflect.Constructor.java line 423
					    public T newInstance(Object ... initargs)
					        throws InstantiationException, IllegalAccessException,
					               IllegalArgumentException, InvocationTargetException
					    {
							// 省略部分代码···
					        @SuppressWarnings("unchecked")
					        // 创建 bean 的终点站到啦!!!这里利用java 反射原理创建实例
					        T inst = (T) ca.newInstance(initargs);
					        return inst;
					    } 
  

到此为止,实例已经创建完毕,接下来我看看bean 的初始化

3.3.2、初始化实例 internalAutoProxyCreator

	protected Object initializeBean(final String beanName, final Object bean, @Nullable RootBeanDefinition mbd) {
		if (System.getSecurityManager() != null) {
			AccessController.doPrivileged((PrivilegedAction) () -> {
				// 3.3.2.1:处理Aware接口的方法回调
				invokeAwareMethods(beanName, bean);
				return null;
			}, getAccessControlContext());
		}
		else {
			invokeAwareMethods(beanName, bean);
		}
		Object wrappedBean = bean;
		if (mbd == null || !mbd.isSynthetic()) {
			// 3.3.2.2:应用后置处理器的postProcessBeforeInitialization()
			wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
		}
		try {
			// 3.3.2.3:执行自定义的初始化方法
			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()) {
			// 3.3.2.4:执行后置处理器的postProcessAfterInitialization();
			wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
		}
		return wrappedBean;
	} 
  

分别解析一下上述代码中含注释的部分

3.3.2.1、处理Aware接口的方法回调

	private void invokeAwareMethods(final String beanName, final Object bean) {
		// 如果没有实现Aware接口,直接退出方法了;这里显然是实现了
		if (bean instanceof Aware) {
			// 没有实现 BeanNameAware
			if (bean instanceof BeanNameAware) {
				((BeanNameAware) bean).setBeanName(beanName);
			}
			// 判断成功,设置类加载器
			if (bean instanceof BeanClassLoaderAware) {
				ClassLoader bcl = getBeanClassLoader();
				if (bcl != null) {
					((BeanClassLoaderAware) bean).setBeanClassLoader(bcl);
				}
			}
			// ☆☆ 判断成功,设置 bean 工厂
			if (bean instanceof BeanFactoryAware) {
				((BeanFactoryAware) bean).setBeanFactory(AbstractAutowireCapableBeanFactory.this);
			}
		}
	}
	// org.springframework.aop.framework.autoproxy.AbstractAdvisorAutoProxyCreator.java line 57
	public void setBeanFactory(BeanFactory beanFactory) {
		// 调用父类方法设置工厂
		super.setBeanFactory(beanFactory);
		if (!(beanFactory instanceof ConfigurableListableBeanFactory)) {
			throw new IllegalArgumentException(
					"AdvisorAutoProxyCreator requires a ConfigurableListableBeanFactory: " + beanFactory);
		}
		// 初始化 bean 工厂,跟进去搂一眼
		initBeanFactory((ConfigurableListableBeanFactory) beanFactory);
	}
		// org.springframework.aop.aspectj.annotation.AnnotationAwareAspectJAutoProxyCreator.java line 79
		protected void initBeanFactory(ConfigurableListableBeanFactory beanFactory) {
		super.initBeanFactory(beanFactory);
		if (this.aspectJAdvisorFactory == null) {
			// 创建了ReflectiveAspectJAdvisorFactory反射机制,相当于把aspectJAdvisorFactory对象通知工厂
			this.aspectJAdvisorFactory = new ReflectiveAspectJAdvisorFactory(beanFactory);
		}
		// 通知适配器,相当于aspectJAdvisorFactory通知到构建器的适配器, 把aspectJAdvisorFactory重新包装了一下
		this.aspectJAdvisorsBuilder =
				new BeanFactoryAspectJAdvisorsBuilderAdapter(beanFactory, this.aspectJAdvisorFactory);
		}

3.3.2.2、应用后置处理器的postProcessBeforeInitialization();

	// org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.java line 417
	public Object applyBeanPostProcessorsBeforeInitialization(Object existingBean, String beanName)
			throws BeansException {
		Object result = existingBean;
		/*在这里接收来自Spring内部的后置处理器的洗礼(postProcessBefore),后置处理大礼包走起
		org.springframework.context.support.ApplicationContextAwareProcessor
		org.springframework.context.support.ApplicationListenerDetector
		org.springframework.context.annotation.ConfigurationClassPostProcessor
		org.springframework.context.support.PostProcessorRegistrationDelegate
		org.springframework.context.annotation.CommonAnnotationBeanPostProcessor
		org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor
		org.springframework.beans.factory.annotation.RequiredAnnotationBeanPostProcessor
		*/
		for (BeanPostProcessor beanProcessor : getBeanPostProcessors()) {
			Object current = beanProcessor.postProcessBeforeInitialization(result, beanName);
			if (current == null) {
				return result;
			}
			result = current;
		}
		return result;
	}		

3.3.2.3、执行自定义的初始化方法

	// org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.java line 1745
	protected void invokeInitMethods(String beanName, final Object bean, @Nullable RootBeanDefinition mbd)
			throws Throwable {
		// 省略部分代码···
		if (mbd != null && bean.getClass() != NullBean.class) {
			// 其实就是声明@Bean注解的时候,指定初始化方法或销毁方法是什么,在这里执行;当前实例类没有设置初始化方法,这里跳过
			String initMethodName = mbd.getInitMethodName();
			if (StringUtils.hasLength(initMethodName) &&
					!(isInitializingBean && "afterPropertiesSet".equals(initMethodName)) &&
					!mbd.isExternallyManagedInitMethod(initMethodName)) {
				invokeCustomInitMethod(beanName, bean, mbd);
			}
		}
	}	

3.3.2.4、执行后置处理器的postProcessAfterInitialization();

	// org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.java line 432
	public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName)
			throws BeansException {
		Object result = existingBean;
		for (BeanPostProcessor beanProcessor : getBeanPostProcessors()) {
			// 同上,在这里接收来自Spring内部的后置处理器的洗礼(postProcessAfter)
			Object current = beanProcessor.postProcessAfterInitialization(result, beanName);
			if (current == null) {
				return result;
			}
			result = current;
		}
		return result;
	}

好了,实例已经创建和初始化完毕了,接下来看看最后一步,

3.3.3、注册实现了Ordered接口的BeanPostProcessor;

代码回到 org.springframework.context.support.PostProcessorRegistrationDelegate line 233

registerBeanPostProcessors(beanFactory, internalPostProcessors);

如果到现在头还没晕,恭喜你,获得最强大脑荣誉勋章一枚!深吸一口气,马上就结束了,跟进去看看

	private static void registerBeanPostProcessors(
			ConfigurableListableBeanFactory beanFactory, List postProcessors) {
                // 将创建成功的BeanPostProcessor对象加入工厂,AOP核心对象创建完成
		for (BeanPostProcessor postProcessor : postProcessors) {
			beanFactory.addBeanPostProcessor(postProcessor);
		}
	}

 

 

你可能感兴趣的:(JAVA基础,Spring)