spring aop源码解析1: 创建、初始化并注册AnnotationAwareAspectJAutoProxyCreator

spring aop的源码解析内容比较多,准备分为三个部分:

1. 创建、初始化并注册AnnotationAwareAspectJAutoProxyCreator

2. AnnotationAwareAspectJAutoProxyCreator拦截切点bean(join point)创建过程并生成proxy(在切点织入切面)的过程

3. 代理对象执行过程分析--构造拦截器链及触发拦截器链

这一篇为第一篇。

如果想要使spring aop功能生效,那么要使用@EnableAspectJAutoProxy注解

1. @EnableAspectJAutoProxy作用

@Import(AspectJAutoProxyRegistrar.class):给容器中导入AspectJAutoProxyRegistrar

@Import(AspectJAutoProxyRegistrar.class)

public @interface EnableAspectJAutoProxy {

 

org.springframework.context.annotation.AspectJAutoProxyRegistrar

class AspectJAutoProxyRegistrar implements ImportBeanDefinitionRegistrar {

 

ImportBeanDefinitionRegistrar在spring ioc中有接触到,其作用是手动注册bean到容器中

org.springframework.aop.config.AopConfigUtils#registerAspectJAnnotationAutoProxyCreatorIfNecessary(org.springframework.beans.factory.support.BeanDefinitionRegistry, java.lang.Object)

return registerOrEscalateApcAsRequired(AnnotationAwareAspectJAutoProxyCreator.class, registry, source);

 

org.springframework.aop.config.AopConfigUtils#registerOrEscalateApcAsRequired

传入的Class 就是 AnnotationAwareAspectJAutoProxyCreator.class

if (registry.containsBeanDefinition(AUTO_PROXY_CREATOR_BEAN_NAME)) {

   

}

RootBeanDefinition beanDefinition = new RootBeanDefinition(cls);

...

registry.registerBeanDefinition(AUTO_PROXY_CREATOR_BEAN_NAME, beanDefinition);

return beanDefinition;

 

/**

 * The bean name of the internally managed auto-proxy creator.

 */

public static final String AUTO_PROXY_CREATOR_BEAN_NAME =

      "org.springframework.aop.config.internalAutoProxyCreator";

 

组件名字是:internalAutoProxyCreator

组件类型是:AnnotationAwareAspectJAutoProxyCreator

流程图:

spring aop源码解析1: 创建、初始化并注册AnnotationAwareAspectJAutoProxyCreator_第1张图片

总结来说,就是@EnableAspectJAutoProxy这个注解

向容器中注册一个名字叫internalAutoProxyCreator

类型是AnnotationAwareAspectJAutoProxyCreator的组件

这个组件我们在spring ioc中也是看到过的

在BeanPostProcessor接口的实现类中,就有这个类

 

2. AnnotationAwareAspectJAutoProxyCreator组件提供了什么功能?

其类图

spring aop源码解析1: 创建、初始化并注册AnnotationAwareAspectJAutoProxyCreator_第2张图片

其实现了BeanPostProcessor:后置处理器(在bean初始化完成前后做事情)

其实现了BeanFactoryAware:调用setBeanFactory,可以装配BeanFactory

 

逐个继承层次各自分析其作用

AbstractAutoProxyCreator

AbstractAutoProxyCreator中有后置处理器的逻辑;

 

注意其区别,一个是Initialization  另一个是Instantiation

也有BeanFactoryAware的逻辑

AbstractAutoProxyCreator.setBeanFactory()

AbstractAdvisorAutoProxyCreator

有BeanFactoryAware的逻辑

override了setBeanFactory

AbstractAdvisorAutoProxyCreator.setBeanFactory()中调用了initBeanFactory()

并没有与后置处理器相关的逻辑

AspectJAwareAdvisorAutoProxyCreator

可以看到这个类中没有与后置处理器和自动装配相关的方法

AnnotationAwareAspectJAutoProxyCreator

initBeanFactory 可以看到其又重写了父类的initBeanFactory方法

并没有与后置处理器相关的逻辑

流程

过程相对复杂,先放一张流程图

spring aop源码解析1: 创建、初始化并注册AnnotationAwareAspectJAutoProxyCreator_第3张图片

1. 传入配置类,创建ioc容器

AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfigOfAOP.class);

2. 注册配置类,调用refresh()刷新容器;

public AnnotationConfigApplicationContext(Class... annotatedClasses) {

   this();

   register(annotatedClasses);

   refresh();

}

3.创建、初始化、注册AnnotationAwareAspectJAutoProxyCreator

refresh方法中有好多个步骤

有一步是registerBeanPostProcessors(beanFactory);

 

org.springframework.context.support.PostProcessorRegistrationDelegate#registerBeanPostProcessors(org.springframework.beans.factory.config.ConfigurableListableBeanFactory, org.springframework.context.support.AbstractApplicationContext)

3.1先获取ioc容器已经定义了的需要创建对象的所有BeanPostProcessor

String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanPostProcessor.class, true, false);

spring aop源码解析1: 创建、初始化并注册AnnotationAwareAspectJAutoProxyCreator_第4张图片

这个internalAutoProxyCreator的类型就是AnnotationAwareAspectJAutoProxyCreator

要按照之前的beanDefination来创建这个后置处理器bean

3.2 给容器中加别的BeanPostProcessor

注册BeanPostProcessorChecker,在BeanPostProcessor实例化期间创建bean时记录信息消息

// 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.
beanFactory.addBeanPostProcessor(new BeanPostProcessorChecker(beanFactory, beanProcessorTargetCount));

把实现PriorityOrdered接口,Ordered接口和剩余的(未实现这两个接口的)BeanPostProcessors进行区分。

// Separate between BeanPostProcessors that implement PriorityOrdered,

// Ordered, and the rest.

List priorityOrderedPostProcessors = new ArrayList();

List internalPostProcessors = new ArrayList();
// First, register the BeanPostProcessors that implement PriorityOrdered.
// Next, register the BeanPostProcessors that implement Ordered.
// Now, register all regular BeanPostProcessors.
 

3.3 优先注册实现了PriorityOrdered接口的BeanPostProcessor;

3.4 再给容器中注册实现了Ordered接口的BeanPostProcessor;

注意,AnnotationAwareAspectJAutoProxyCreator就实现了Ordered接口

所以在这里去getBean

// Next, register the BeanPostProcessors that implement Ordered.

List orderedPostProcessors = new ArrayList();

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,实际上就是创建BeanPostProcessor对象,保存在容器中;

 

         创建internalAutoProxyCreator的BeanPostProcessor,类型是

AnnotationAwareAspectJAutoProxyCreator

3.4.1 创建Bean的实例

org.springframework.beans.factory.support.AbstractBeanFactory#doGetBean

先从缓存中获取当前bean,如果能获取到,说明bean是之前被创建过的,直接使用,否则再创建;

// Eagerly check singleton cache for manually registered singletons.

Object sharedInstance = getSingleton(beanName);

只要创建好的Bean都会被缓存起来,保证单实例Bean只会被创建一次

 

org.springframework.beans.factory.support.DefaultSingletonBeanRegistry#getSingleton(java.lang.String, boolean)

第一次获取应该是获取不到的,返回null

 

之后继续向下getObject

 

来create 这个后置处理器bean

 

org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#createBean(java.lang.String, org.springframework.beans.factory.support.RootBeanDefinition, java.lang.Object[])

这个AbstractAutowireCapableBeanFactory中的createBean方法是核心方法

作用:Central method of this class: creates a bean instance, populates the bean instance, applies post-processors, etc

spring aop源码解析1: 创建、初始化并注册AnnotationAwareAspectJAutoProxyCreator_第5张图片

注意这里:

Give BeanPostProcessors a chance to return a proxy instead of the target bean instance.

 

我们知道AnnotationAwareAspectJAutoProxyCreator其先实现了

InstantiationAwarePostBeanProcessor,再实现PostBeanProcessor

而InstantiationAwarePostBeanProcessor提供了两个方法,即这个接口给PostBeanProcessor赋能了

spring aop源码解析1: 创建、初始化并注册AnnotationAwareAspectJAutoProxyCreator_第6张图片

org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator#postProcessBeforeInstantiation

注意其注解:

如果我们有自定义TargetSource,请在此处创建代理。

禁止目标bean的不必要的默认实例化:

TargetSource将以自定义方式处理目标实例。

spring aop源码解析1: 创建、初始化并注册AnnotationAwareAspectJAutoProxyCreator_第7张图片

可以看到,如果实现了InstantiationAwarePostBeanProcessor并有自定义的TargetSource,那么就在bean初始化之前返回proxy对象。如果返回值不为null,那么就沿用PostBeanProcessor,其调用

org.springframework.aop.framework.AbstractAdvisingBeanPostProcessor#postProcessAfterInitialization

注意其注释:Add our local Advisor to the existing proxy's Advisor chain...

spring aop源码解析1: 创建、初始化并注册AnnotationAwareAspectJAutoProxyCreator_第8张图片

实际上返回结果为null,于是继续向下执行

Object beanInstance = doCreateBean(beanName, mbdToUse, args);

 

org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#doCreateBean

if (instanceWrapper == null) {

   instanceWrapper = createBeanInstance(beanName, mbd, args);

}

 

 

org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#instantiateBean

 

最后得到instanceWrapper并将其赋值给bean

至此,就生成了这个名字叫internalAutoProxyCreator

类型是AnnotationAwareAspectJAutoProxyCreator的组件

spring aop源码解析1: 创建、初始化并注册AnnotationAwareAspectJAutoProxyCreator_第9张图片

3.4.2 populateBean;给bean的各种属性赋值

 

// Initialize the bean instance.

Object exposedObject = bean;

try {

   populateBean(beanName, mbd, instanceWrapper);

   if (exposedObject != null) {

      exposedObject = initializeBean(beanName, exposedObject, mbd);

   }

}

 

org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#doCreateBean

 

 

3.4.3 initializeBean:初始化bean;

org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#initializeBean(java.lang.String, java.lang.Object, org.springframework.beans.factory.support.RootBeanDefinition)

protected Object initializeBean(final String beanName, final Object bean, RootBeanDefinition mbd) {

   if (System.getSecurityManager() != null) {

        }

   else {

      invokeAwareMethods(beanName, bean);

   }



   Object wrappedBean = bean;

   if (mbd == null || !mbd.isSynthetic()) {

      wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);

   }



   try {

      invokeInitMethods(beanName, wrappedBean, mbd);

   }

   catch (Throwable ex) {



   }



   if (mbd == null || !mbd.isSynthetic()) {

      wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);

   }

   return wrappedBean;

}

3.4.3.1 invokeAwareMethods():处理Aware接口的方法回调

spring aop源码解析1: 创建、初始化并注册AnnotationAwareAspectJAutoProxyCreator_第10张图片

protected void initBeanFactory(ConfigurableListableBeanFactory beanFactory) {

   super.initBeanFactory(beanFactory);

   if (this.aspectJAdvisorFactory == null) {

      this.aspectJAdvisorFactory = new ReflectiveAspectJAdvisorFactory(beanFactory);

   }

   this.aspectJAdvisorsBuilder =

         new BeanFactoryAspectJAdvisorsBuilderAdapter(beanFactory, this.aspectJAdvisorFactory);

}

得到了aspectJAdvisorFactory及aspectJAdvisorsBuilder

 

3.4.3.2 applyBeanPostProcessorsBeforeInitialization():

应用后置处理器的postProcessBeforeInitialization()

3.4.3.3 invokeInitMethods();

执行自定义的初始化方法

3.4.3.4 applyBeanPostProcessorsAfterInitialization();

执行后置处理器的postProcessAfterInitialization()

 

最后

org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#doCreateBean

返回

 

 

返回到

org.springframework.beans.factory.support.DefaultSingletonBeanRegistry#getSingleton(java.lang.String, org.springframework.beans.factory.ObjectFactory)

addSingleton(beanName, singletonObject);

 

最后返回到最初的调用处

org.springframework.context.support.PostProcessorRegistrationDelegate#registerBeanPostProcessors(org.springframework.beans.factory.config.ConfigurableListableBeanFactory, org.springframework.context.support.AbstractApplicationContext)

BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);

 

3.4.4 至此AnnotationAwareAspectJAutoProxyCreator创建成功并初始化

 

 

之后调用

sortPostProcessors(orderedPostProcessors, beanFactory);

registerBeanPostProcessors(beanFactory, orderedPostProcessors);

 

/**

 * Register the given BeanPostProcessor beans.

 */

private static void registerBeanPostProcessors(

      ConfigurableListableBeanFactory beanFactory, List postProcessors) {



   for (BeanPostProcessor postProcessor : postProcessors) {

      beanFactory.addBeanPostProcessor(postProcessor);

   }

}

把创建并初始化好的internalAutoProxyCreator注册到BeanFactory中(beanFactory就是容器,容器大类上分两种,beanFactory和applicationContext)

 

3.5 注册没实现优先级接口的BeanPostProcessor;

 

以上就是创建、初始化和注册AnnotationAwareAspectJAutoProxyCreator的过程

你可能感兴趣的:(阅读源码,spring,aop,源码解析)