Spring AOP原理之注册AnnotationAwareAspectJAutoProxyCreator

目录

1. 说明

2. BeanPostProcessor的创建过程

3. 创建AnnotationAwareAspectJAutoProxyCreator

4. 注册AnnotationAwareAspectJAutoProxyCreator 

1. 说明

AnnotationAwareAspectJAutoProxyCreator作为BeanPostProcessor,在IOC容器初始化的时候,先会创建和注册到IOC容器中;

2. BeanPostProcessor的创建过程

1) . 通过配置类,创建IOC容器
2).  注册配置类,调用refresh();刷新容器;
3).  刷新容器过程中,通过registerBeanPostProcessors(beanFactory)注册所有BeanPostProcessor;
       3.1) 先获取ioc容器已经定义了的需要创建对象的所有BeanPostProcessor
       3.2) 给容器中加别的BeanPostProcessor
       3.3) 优先注册实现了PriorityOrdered接口的BeanPostProcessor;
       3.4) 再给容器中注册实现了Ordered接口的BeanPostProcessor;
       3.5) 注册没实现优先级接口的BeanPostProcessor;

注册BeanPostProcessor的具体代码实现在org.springframework.context.support.PostProcessorRegistrationDelegate.registerBeanPostProcessors(ConfigurableListableBeanFactory, AbstractApplicationContext),代码如下:

public static void registerBeanPostProcessors(
			ConfigurableListableBeanFactory beanFactory, AbstractApplicationContext applicationContext) {

	// 获取所有BeanPostProcessor的name,其中就包含“org.springframework.aop.config.internalAutoProxyCreator”
	String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanPostProcessor.class, true, false);

	// Register BeanPostProcessorChecker that logs an info message when
	// a bean is created during BeanPostProcessor instantiation, i.e. when
	// a bean is not eligible for getting processed by all BeanPostProcessors.
	int beanProcessorTargetCount = beanFactory.getBeanPostProcessorCount() + 1 + postProcessorNames.length;
	beanFactory.addBeanPostProcessor(new BeanPostProcessorChecker(beanFactory, beanProcessorTargetCount));

	// Separate between BeanPostProcessors that implement PriorityOrdered,
	// Ordered, and the rest.
	// 分离实现了PriorityOrdered,Ordered和其他剩下的BeanPostProcessor;
	// 实现了PriorityOrdered接口的BeanPostProcessor的集合
	List<BeanPostProcessor> priorityOrderedPostProcessors = new ArrayList<BeanPostProcessor>(); 
	// 内部BeanPostProcessor
	List<BeanPostProcessor> internalPostProcessors = new ArrayList<BeanPostProcessor>();
	// 实现了Ordered接口的BeanPostProcessor的name集合
	List<String> orderedPostProcessorNames = new ArrayList<String>();
	// 其他剩下BeanPostProcessor的name集合
	List<String> nonOrderedPostProcessorNames = new ArrayList<String>();
	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);
		}
	}

	// First, register the BeanPostProcessors that implement PriorityOrdered.
	// 排序和注册实现了PriorityOrdered的BeanPostProcessor,优先级最高
	sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
	registerBeanPostProcessors(beanFactory, priorityOrderedPostProcessors);

	// Next, register the BeanPostProcessors that implement Ordered.
	// 实现了Ordered接口的BeanPostProcessor集合
	List<BeanPostProcessor> orderedPostProcessors = new ArrayList<BeanPostProcessor>();
	for (String ppName : orderedPostProcessorNames) {
		BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
		orderedPostProcessors.add(pp);
		if (pp instanceof MergedBeanDefinitionPostProcessor) {
			internalPostProcessors.add(pp);
	}
	}
	// 排序和注册实现了Ordered的BeanPostProcessor,优先级次之
	sortPostProcessors(orderedPostProcessors, beanFactory);
	registerBeanPostProcessors(beanFactory, orderedPostProcessors);

	// Now, register all regular BeanPostProcessors.
	// 其他剩下BeanPostProcessor的name集合
	List<BeanPostProcessor> nonOrderedPostProcessors = new ArrayList<BeanPostProcessor>();
	for (String ppName : nonOrderedPostProcessorNames) {
		BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
		nonOrderedPostProcessors.add(pp);
		if (pp instanceof MergedBeanDefinitionPostProcessor) {
			internalPostProcessors.add(pp);
		}
	}
	// 注册其他没有实现PriorityOrdered和Ordered的BeanPostProcessor,优先级再次之
	registerBeanPostProcessors(beanFactory, nonOrderedPostProcessors);

	// Finally, re-register all internal BeanPostProcessors.
	// 注册实现了内部的BeanPostProcessor,优先级最小
	sortPostProcessors(internalPostProcessors, beanFactory);
	registerBeanPostProcessors(beanFactory, internalPostProcessors);

	// Re-register post-processor for detecting inner beans as ApplicationListeners,
	// moving it to the end of the processor chain (for picking up proxies etc).
	beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(applicationContext));
}

3. 创建AnnotationAwareAspectJAutoProxyCreator

AnnotationAwareAspectJAutoProxyCreator作为BeanPostProcessor的子类,在注册BeanPostProcessor的时候,也会将AnnotationAwareAspectJAutoProxyCreator注册到IOC容器中,所谓注册,实际上就是创建BeanPostProcessor对象,初始化之后,保存在容器中,这里就会创建和注册AnnotationAwareAspectJAutoProxyCreator,name是“org.springframework.aop.config.internalAutoProxyCreator”;

创建AnnotationAwareAspectJAutoProxyCreator的过程如下:

1). 创建AnnotationAwareAspectJAutoProxyCreator的实例
2). populateBean;给AnnotationAwareAspectJAutoProxyCreator的各种属性赋值
3). initializeBean:初始化AnnotationAwareAspectJAutoProxyCreator;
     3.1). invokeAwareMethods():处理Aware接口的方法回调
     3. 2). applyBeanPostProcessorsBeforeInitialization():应用后置处理器的postProcessBeforeInitialization()
     3. 3). invokeInitMethods();执行自定义的初始化方法
     3. 4). applyBeanPostProcessorsAfterInitialization();执行后置处理器的postProcessAfterInitialization();
4).  BeanPostProcessor(AnnotationAwareAspectJAutoProxyCreator)创建成功;–》aspectJAdvisorsBuilder

代码实现实现在org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(String, RootBeanDefinition, Object[]),具体代码如下:

protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final Object[] args)
			throws BeanCreationException {

	// Instantiate the bean.
	BeanWrapper instanceWrapper = null;
	if (mbd.isSingleton()) {
		instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
	}
	if (instanceWrapper == null) {
		// 创建组件AnnotationAwareAspectJAutoProxyCreator
		instanceWrapper = createBeanInstance(beanName, mbd, args);
	}
	final Object bean = (instanceWrapper != null ? instanceWrapper.getWrappedInstance() : null);
	Class<?> beanType = (instanceWrapper != null ? instanceWrapper.getWrappedClass() : null);
	mbd.resolvedTargetType = beanType;

	// Allow post-processors to modify the merged bean definition.
	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;
		}
	}

	// 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.isDebugEnabled()) {
			logger.debug("Eagerly caching bean '" + beanName +
					"' to allow for resolving potential circular references");
		}
		addSingletonFactory(beanName, new ObjectFactory<Object>() {
			@Override
			public Object getObject() throws BeansException {
				return getEarlyBeanReference(beanName, mbd, bean);
			}
		});
	}

	// Initialize the bean instance.
	Object exposedObject = bean;
	try {
		// 给组件AnnotationAwareAspectJAutoProxyCreator赋值
		populateBean(beanName, mbd, instanceWrapper);
		if (exposedObject != null) {
			//初始化AnnotationAwareAspectJAutoProxyCreator
			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<String> actualDependentBeans = new LinkedHashSet<String>(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 " +
							"'getBeanNamesOfType' with the 'allowEagerInit' flag turned off, for example.");
				}
			}
		}
	}

	// Register bean as disposable.
	try {
		registerDisposableBeanIfNecessary(beanName, bean, mbd);
	}
	catch (BeanDefinitionValidationException ex) {
		throw new BeanCreationException(
				mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex);
	}
	// 返回创建的组件AnnotationAwareAspectJAutoProxyCreator实例;
	return exposedObject;
}

其中org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(String, Object, RootBeanDefinition)的实现如下:

protected Object initializeBean(final String beanName, final Object bean, RootBeanDefinition mbd) {
	if (System.getSecurityManager() != null) {
		AccessController.doPrivileged(new PrivilegedAction<Object>() {
			@Override
			public Object run() {
				invokeAwareMethods(beanName, bean);
				return null;
			}
		}, getAccessControlContext());
	}
	else {
		// 调用Aware子接口的方法,因为AnnotationAwareAspectJAutoProxyCreator实现了BeanFactoryAware接口,所以这里会调用
		invokeAwareMethods(beanName, bean);
	}

	Object wrappedBean = bean;
	if (mbd == null || !mbd.isSynthetic()) {
		// 创建对象初始化的时候,执行已经在容器中的所有BeanPostProcessor的postProcessBeforeInitialization
		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()) {
		// 创建对象初始化的时候,执行已经在容器中的所有BeanPostProcessor的postProcessAfterInitialization
		wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
	}
	return wrappedBean;
}

在执行initializeBean的invokeAwareMethods方法的时候,调用到AnnotationAwareAspectJAutoProxyCreator的父接口org.springframework.aop.framework.autoproxy.AbstractAdvisorAutoProxyCreator的setBeanFactory方法,具体代码如下:

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

其中initBeanFactory调用的是org.springframework.aop.aspectj.annotation.AnnotationAwareAspectJAutoProxyCreator.initBeanFactory(ConfigurableListableBeanFactory),其代码如下:

@Override
protected void initBeanFactory(ConfigurableListableBeanFactory beanFactory) {
	super.initBeanFactory(beanFactory);
	// 将BeanFatory包装到ReflectiveAspectJAdvisorFactory和BeanFactoryAspectJAdvisorsBuilderAdapter,并创建对象
	if (this.aspectJAdvisorFactory == null) {
		this.aspectJAdvisorFactory = new ReflectiveAspectJAdvisorFactory(beanFactory);
	}
	this.aspectJAdvisorsBuilder =
			new BeanFactoryAspectJAdvisorsBuilderAdapter(beanFactory, this.aspectJAdvisorFactory);
}

到这里AnnotationAwareAspectJAutoProxyCreator的实例被创建,且Aware相关接口被调用,接下来是把AnnotationAwareAspectJAutoProxyCreator的实例注册到IOC容器中;

4. 注册AnnotationAwareAspectJAutoProxyCreator 

将AnnotationAwareAspectJAutoProxyCreator注册到IOC容器中,具体调用在org.springframework.context.support.PostProcessorRegistrationDelegate.registerBeanPostProcessors(ConfigurableListableBeanFactory, AbstractApplicationContext) 的registerBeanPostProcessors方法,具体实现如下:

/**
 * Register the given BeanPostProcessor beans.
 */
private static void registerBeanPostProcessors(
		ConfigurableListableBeanFactory beanFactory, List<BeanPostProcessor> postProcessors) {

	for (BeanPostProcessor postProcessor : postProcessors) {
		beanFactory.addBeanPostProcessor(postProcessor);
	}
}

到这里,AnnotationAwareAspectJAutoProxyCreator就已经被创建,且调用AnnotationAwareAspectJAutoProxyCreator的Aware相关接口,然后已经注册到IOC容器中;

 

    原文作者:AOP
    原文地址: https://blog.csdn.net/luojinbai/article/details/86709649
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞