Spring AOP原理之AnnotationAwareAspectJAutoProxyCreator分析

 

目录

1. 说明

2. AnnotationAwareAspectJAutoProxyCreator的继承关系

3. 关键类分析

1. 说明

@EnableAspectJAutoProxy通过@Import导入AspectJAutoProxyRegistrar.class,然后AspectJAutoProxyRegistrar是ImportBeanDefinitionRegistrar接口的实现类,又导入了AnnotationAwareAspectJAutoProxyCreator;

2. AnnotationAwareAspectJAutoProxyCreator的继承关系

AnnotationAwareAspectJAutoProxyCreator的继承关系如下:
        AnnotationAwareAspectJAutoProxyCreator
            –AspectJAwareAdvisorAutoProxyCreator
                –AbstractAdvisorAutoProxyCreator
                    –AbstractAutoProxyCreator
                        — ProxyProcessorSupport, SmartInstantiationAwareBeanPostProcessor, BeanFactoryAware
        其中
        ProxyProcessorSupport
            –ProxyConfig,Ordered,BeanClassLoaderAware,AopInfrastructureBean
        SmartInstantiationAwareBeanPostProcessor
            –InstantiationAwareBeanPostProcessor
                –BeanPostProcessor
        BeanFactoryAware
            –Aware

3. 关键类分析

  • 3.1 BeanFactoryAware, Aware

容器中每个组件被创建和属性赋值之后,初始化组件的时候,会调用Aware的子接口的方法,具体实现在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接口,执行Aware的子接口中的方法
		invokeAwareMethods(beanName, bean);
	}

	Object wrappedBean = bean;
	if (mbd == null || !mbd.isSynthetic()) {
		//执行所有BeanPostProcessor的postProcessBeforeInitialization的方法
		wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
	}

	try {
		//执行所有初始化方法:实现InitializingBean的afterPropertiesSet()方法,@Bean中init-method指定的方法和@PostConstruct标记的方法;
		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;
}

其中,org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeAwareMethods(String, Object)代码如下:

private void invokeAwareMethods(final String beanName, final Object bean) {
	if (bean instanceof Aware) {
		if (bean instanceof BeanNameAware) {
			((BeanNameAware) bean).setBeanName(beanName);
		}
		if (bean instanceof BeanClassLoaderAware) {
			((BeanClassLoaderAware) bean).setBeanClassLoader(getBeanClassLoader());
		}
		if (bean instanceof BeanFactoryAware) {
			// 通过setBeanFactory方法给BeanFactoryAware的所有实现类注入BeanFactory实例
			((BeanFactoryAware) bean).setBeanFactory(AbstractAutowireCapableBeanFactory.this);
		}
	}
}
  • 3.2 BeanPostProcessor

  BeanPostProcessor中接口中有两个方法: 分别是 postProcessBeforeInitialization()和 postProcessAfterInitialization(),两个方法是在组件被创建,属性赋值之后,初始化组件的时候,调用Aware子接口方法,然后调用ostProcessBeforeInitialization接口,再调用调用所有自定义初始化方法,再调用postProcessAfterInitialization方法;具体实现在 org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(String, Object, RootBeanDefinition)中;

  • 3.3  InstantiationAwareBeanPostProcessor

nstantiationAwareBeanPostProcessor实现了BeanPostProcessor接口,还扩展了如下3个方法:

Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) throws BeansException;

boolean postProcessAfterInstantiation(Object bean, String beanName) throws BeansException;

PropertyValues postProcessPropertyValues(PropertyValues pvs, PropertyDescriptor[] pds, Object bean, String beanName) throws BeansException;

InstantiationAwareBeanPostProcessor中的postProcessBeforeInstantiation是在组件被创建之前被调用(区别于BeanPostProcessor中的两个方法,BeanPostProcessor是在组件创建完成,属性赋值完成之后,调用组件自定义初始化方法的时候被调用),具体被调用是在的代码org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(String, RootBeanDefinition, Object[]),代码如下:

/**
 * Central method of this class: creates a bean instance,
 * populates the bean instance, applies post-processors, etc.
 * @see #doCreateBean
*/
@Override
protected Object createBean(String beanName, RootBeanDefinition mbd, Object[] args) throws BeanCreationException {
	if (logger.isDebugEnabled()) {
		logger.debug("Creating instance of bean '" + beanName + "'");
	}
	RootBeanDefinition mbdToUse = mbd;

	// Make sure bean class is actually resolved at this point, and
	// clone the bean definition in case of a dynamically resolved Class
	// which cannot be stored in the shared merged bean definition.
	Class<?> resolvedClass = resolveBeanClass(mbd, beanName);
	if (resolvedClass != null && !mbd.hasBeanClass() && mbd.getBeanClassName() != null) {
		mbdToUse = new RootBeanDefinition(mbd);
		mbdToUse.setBeanClass(resolvedClass);
	}

	// Prepare method overrides.
	try {
		mbdToUse.prepareMethodOverrides();
	}
	catch (BeanDefinitionValidationException ex) {
		throw new BeanDefinitionStoreException(mbdToUse.getResourceDescription(),
				beanName, "Validation of method overrides failed", ex);
	}

	try {
		// Give BeanPostProcessors a chance to return a proxy instead of the target bean instance.
		// 尝试通过BeanPostProcessors来创建组件的代理,并返回
		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);
	}

	Object beanInstance = doCreateBean(beanName, mbdToUse, args);
	if (logger.isDebugEnabled()) {
		logger.debug("Finished creating instance of bean '" + beanName + "'");
	}
	return beanInstance;
}

其中,org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.resolveBeforeInstantiation(String, RootBeanDefinition)的代码如下:

protected Object resolveBeforeInstantiation(String beanName, RootBeanDefinition mbd) {
	Object bean = null;
	if (!Boolean.FALSE.equals(mbd.beforeInstantiationResolved)) {
		// Make sure bean class is actually resolved at this point.
		if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
			Class<?> targetType = determineTargetType(beanName, mbd);
			if (targetType != null) {
				// 这里
				bean = applyBeanPostProcessorsBeforeInstantiation(targetType, beanName);
				if (bean != null) {
					// 如果创建出组件的代理,这里还是调用所有BeanPostProcessor的postProcessAfterInitialization方法,执行组件的初始化之后的方法调用
					bean = applyBeanPostProcessorsAfterInitialization(bean, beanName);
				}
			}
		}
		mbd.beforeInstantiationResolved = (bean != null);
	}
	return bean;
}

其中,org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsBeforeInstantiation(Class<?>, String)的代码如下:

protected Object applyBeanPostProcessorsBeforeInstantiation(Class<?> beanClass, String beanName) {
	for (BeanPostProcessor bp : getBeanPostProcessors()) {
		//判断是否是InstantiationAwareBeanPostProcessor,如果是
		if (bp instanceof InstantiationAwareBeanPostProcessor) { 
			InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
			// 调用InstantiationAwareBeanPostProcessor的postProcessBeforeInstantiation方法,尝试创建组件的代理
			Object result = ibp.postProcessBeforeInstantiation(beanClass, beanName);
			if (result != null) {
				return result;
			}
		}
	}
	return null;
}
  • 3.4 Ordered

 Ordered接口是指定组件组件创建的优先级,优先级高的先被创建,类似的还有PriorityOrdered接口,在导入BeanPostProcessor的过程中,会先导入实现了PriorityOrdered的BeanPostProcessor,然后再导入实现了Ordered接口的BeanPostProcessor,最后再导入剩下其他的BeanPostProcessor,具体的代码实现在org.springframework.context.support.PostProcessorRegistrationDelegate.registerBeanPostProcessors(ConfigurableListableBeanFactory, AbstractApplicationContext)中;
  

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