dtcms map转string Android防重复点击 CGLib动态代理 Apache Apache Pivot教程 events vector replace uwp usb mui vue开发 vue安装教程 郑州网站建设 angular视频 jquery循环遍历 mysql操作日志 solr索引 ai如何导出矢量图 完美解决cpu利用率低 python的extend python中不等于 java实战 java获取月份 java语言 java获取当前ip java网课 ie模拟器 rewritebase 倒计时计时器 js延迟加载 电子书制作软件 虚拟打印机安装 mpg格式转换 skycc组合营销软件 linux定时任务 毕业证件照 流媒体下载 截取字符串
当前位置: 首页 > 学习教程  > 编程语言

spring (三) 【源码】AOP原理之@EnableAspectJAutoProxy注解对bean生命周期的影响

2020/11/4 15:13:17 文章标签:

怎么使用AOP 我们在使用AOP的时候,大致分为三步 1)、将业务逻辑组件和切面类都加入到容器中;告诉Spring哪个是切面类(Aspect)2)、在切面类上的每一个通知方法上标注通知注解,告诉Spring何时何…

怎么使用AOP

我们在使用AOP的时候,大致分为三步

  • 1)、将业务逻辑组件和切面类都加入到容器中;告诉Spring哪个是切面类(@Aspect)
  • 2)、在切面类上的每一个通知方法上标注通知注解,告诉Spring何时何地运行(切入点表达式)
  • 3)、开启基于注解的aop模式;@EnableAspectJAutoProxy(如果是spring boot项目,则引入AOP的stater但还是要引入@EnableAspectJAutoProxy注解)

那么我们就分析一下@EnableAspectJAutoProxy注解的作用

@EnableAspectJAutoProxy的作用

可以看到这个注解使用@Import引入了AspectJAutoProxyRegistrar类

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Import(AspectJAutoProxyRegistrar.class)
public @interface EnableAspectJAutoProxy {

看一下AspectJAutoProxyRegistrar

class AspectJAutoProxyRegistrar implements ImportBeanDefinitionRegistrar {

   /**
    * Register, escalate, and configure the AspectJ auto proxy creator based on the value
    * of the @{@link EnableAspectJAutoProxy#proxyTargetClass()} attribute on the importing
    * {@code @Configuration} class.
    */
   @Override
   public void registerBeanDefinitions(
         AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {

      AopConfigUtils.registerAspectJAnnotationAutoProxyCreatorIfNecessary(registry);

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

}

这个来实现了ImportBeanDefinitionRegistrar接口,会调用registerBeanDefinitions方法往容器中注册一个组件
spring (一)注册组件,那么我们跟踪registerAspectJAnnotationAutoProxyCreatorIfNecessary这个方法看看到底做了什么,发现会使用AopConfigUtils来注册或者升级一个给容器中注册一个AnnotationAwareAspectJAutoProxyCreator;

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

private static BeanDefinition registerOrEscalateApcAsRequired(Class<?> cls, BeanDefinitionRegistry registry, 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);
   registry.registerBeanDefinition(AUTO_PROXY_CREATOR_BEAN_NAME, beanDefinition);
   return beanDefinition;
}

既然注册了一个AnnotationAwareAspectJAutoProxyCreator类型的bean到容器,那么接下来我们查看一下

AnnotationAwareAspectJAutoProxyCreator的继承关系

AnnotationAwareAspectJAutoProxyCreator extends
AnnotationAwareAspectJAutoProxyCreator extends
AspectJAwareAdvisorAutoProxyCreator extends
AbstractAdvisorAutoProxyCreator extends
AbstractAutoProxyCreator
implements SmartInstantiationAwareBeanPostProcessor, BeanFactoryAware

看到这个继承关系,就应该关注整个体系中实现的后置处理器的方法以及BeanFactory的方法,我们发现:

(1) AbstractAutoProxyCreator.setBeanFactory()方法以及
后置处理器的逻辑postProcessBeforeInstantiation方法

(2) AbstractAdvisorAutoProxyCreator这个类有setBeanFactory()方法
首先调用父类的setBeanFactory方法,然后调用initBeanFactory方法

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

(3)AnnotationAwareAspectJAutoProxyCreator里面有initBeanFactory()方法

接下来要做的就是看看这些方法都做了什么

调试源码@EnableAspectJAutoProxy

配置类

@EnableAspectJAutoProxy
@Configuration
public class MainConfigOfAOP {
    
   //业务逻辑类加入容器中
   @Bean
   public MyCalculator calculator(){
      return new MyCalculator();
   }

   //切面类加入到容器中
   @Bean
   public LogAspects logAspects(){
      return new LogAspects();
   }
}

业务逻辑类很简单

public class MyCalculator {
   
   public int div(int i,int j){
      System.out.println("MathCalculator...div...");
      return i/j;    
   }

}

然后是切面类

@Aspect
public class LogAspects {
   
   //抽取公共的切入点表达式
   //1、本类引用
   //2、其他的切面引用
   @Pointcut("execution(public int com.ethan.aop.MyCalculator.*(..))")
   public void pointCut(){};
   
   //@Before在目标方法之前切入;切入点表达式(指定在哪个方法切入)
   @Before("pointCut()")
   public void logStart(JoinPoint joinPoint){
      Object[] args = joinPoint.getArgs();
      System.out.println(""+joinPoint.getSignature().getName()+"运行。。。@Before:参数列表是:{"+Arrays.asList(args)+"}");
   }
   
   @After("com.ethan.aop.LogAspects.pointCut()")
   public void logEnd(JoinPoint joinPoint){
      System.out.println(""+joinPoint.getSignature().getName()+"结束。。。@After");
   }
   
   //JoinPoint一定要出现在参数表的第一位
   @AfterReturning(value="pointCut()",returning="result")
   public void logReturn(JoinPoint joinPoint,Object result){
      System.out.println(""+joinPoint.getSignature().getName()+"正常返回。。。@AfterReturning:运行结果:{"+result+"}");
   }
   
   @AfterThrowing(value="pointCut()",throwing="exception")
   public void logException(JoinPoint joinPoint,Exception exception){
      System.out.println(""+joinPoint.getSignature().getName()+"异常。。。异常信息:{"+exception+"}");
   }

   @Around(value="pointCut()")
   public void logAround(ProceedingJoinPoint joinPoint) throws Throwable {
      System.out.println("around before proceed");
      joinPoint.proceed();
      System.out.println("around after proceed ");
   }

}

首先进入refresh()方法

public AnnotationConfigApplicationContext(Class<?>... annotatedClasses) {
   this();
   register(annotatedClasses);
   refresh();
}

然后进入方法registerBeanPostProcessors注册bean的后置处理器来方便拦截bean的创建;

// Register bean processors that intercept bean creation.
registerBeanPostProcessors(beanFactory);

跟进registerBeanPostProcessors源码

public static void registerBeanPostProcessors(
      ConfigurableListableBeanFactory beanFactory, AbstractApplicationContext applicationContext) {
//先获取ioc容器已经定义了的需要创建对象的所有BeanPostProcessor
   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.
   List<BeanPostProcessor> priorityOrderedPostProcessors = new ArrayList<BeanPostProcessor>();
   List<BeanPostProcessor> internalPostProcessors = new ArrayList<BeanPostProcessor>();
   List<String> orderedPostProcessorNames = new ArrayList<String>();
   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);
      }
   }
    //优先处理实现了PriorityOrdered的处理器
   // First, register the BeanPostProcessors that implement PriorityOrdered.
   sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
   registerBeanPostProcessors(beanFactory, priorityOrderedPostProcessors);
   //接下里处理实现了Ordered的处理器
   // Next, register the BeanPostProcessors that implement Ordered.
   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);
      }
   }
   sortPostProcessors(orderedPostProcessors, beanFactory);
   registerBeanPostProcessors(beanFactory, orderedPostProcessors);
	//接下来注册没实现优先级接口的BeanPostProcessor;
   // Now, register all regular BeanPostProcessors.
   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);
      }
   }
   //把BeanPostProcessor注册到BeanFactory中
   registerBeanPostProcessors(beanFactory, nonOrderedPostProcessors);

   // Finally, re-register all internal BeanPostProcessors.
   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));
}

    1 )先获取ioc容器已经定义了的需要创建对象的所有BeanPostProcessor
    2) 给容器中加别的BeanPostProcessor
    3 )优先注册实现了PriorityOrdered接口的BeanPostProcessor;
    4) 再给容器中注册实现了Ordered接口的BeanPostProcessor;
因为【AnnotationAwareAspectJAutoProxyCreator】实现了Ordered接口,所以AnnotationAwareAspectJAutoProxyCreator这个BeanPostProcessor在此时注册

List<BeanPostProcessor> orderedPostProcessors = new ArrayList<BeanPostProcessor>();
for (String ppName : orderedPostProcessorNames) {
	//创建AnnotationAwareAspectJAutoProxyCreator
   BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
   orderedPostProcessors.add(pp);
   if (pp instanceof MergedBeanDefinitionPostProcessor) {
      internalPostProcessors.add(pp);
   }
}

      下面再复习一下bean的生生命周期
        1)、创建Bean的实例
        2)、populateBean;给bean的各种属性赋值
        3)、initializeBean:初始化bean;
            1)、invokeAwareMethods():处理Aware接口的方法回调
            2)、applyBeanPostProcessorsBeforeInitialization():应用后置处理器的postProcessBeforeInitialization()
            3)、invokeInitMethods();执行自定义的初始化方法
            4)、applyBeanPostProcessorsAfterInitialization();执行后置处理器的postProcessAfterInitialization();
 
    5 )接下来注册没实现优先级接口的BeanPostProcessor;

    6)、把BeanPostProcessor注册到BeanFactory中; beanFactory.addBeanPostProcessor(postProcessor);


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

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

至此通过@EnableAspectJAutoProxy这个注解想容器中添加了AnnotationAwareAspectJAutoProxyCreator组件

AnnotationAwareAspectJAutoProxyCreator作为后置处理器的作用

在refresh方法中,已经通过了registerBeanPostProcessors注册了后置处理器,但还是有别的组件类型没有被注册,接下来看这个方法

// Instantiate all remaining (non-lazy-init) singletons.
finishBeanFactoryInitialization(beanFactory);

顾名思义,实例化剩下的bean到容器中
在bean的生命周期中,所有的后置处理器都是参与其中的,不难想象,接下来我们要看AnnotationAwareAspectJAutoProxyCreator对剩下的bean的实例化做了什么,跟进源码,在finishBeanFactoryInitialization方法中最后调用了来实例化剩下的bean

// Instantiate all remaining (non-lazy-init) singletons.
beanFactory.preInstantiateSingletons();

可以看到该继续跟进到了getBean(beanName);方法,而beanName则是直接从容器中获得的所有定义的beanDefinitionNames遍历所得

List<String> beanNames = new ArrayList<String>(this.beanDefinitionNames);
//代码有省略
for (String beanName : beanNames) {
   RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);
   if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {
      if (isFactoryBean(beanName)) {
         final FactoryBean<?> factory = (FactoryBean<?>) getBean(FACTORY_BEAN_PREFIX + beanName);
         boolean isEagerInit;
         if (System.getSecurityManager() != null && factory instanceof SmartFactoryBean) {
            isEagerInit = AccessController.doPrivileged(new PrivilegedAction<Boolean>() {
               @Override
               public Boolean run() {
                  return ((SmartFactoryBean<?>) factory).isEagerInit();
               }
            }, getAccessControlContext());
         }
         else {
            isEagerInit = (factory instanceof SmartFactoryBean &&
                  ((SmartFactoryBean<?>) factory).isEagerInit());
         }
         if (isEagerInit) {
            getBean(beanName);
         }
      }
      else {
      	//执行getBean方法来实例化bean
         getBean(beanName);
      }
   }
}

同样实例化bean的调用链为getBean->doGetBean()->getSingleton()->getObject()->createBean()
接下来看createBean的源码

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 {
   	//注意此处,给BeanPostProcessors 一个机会来返回一个代理对象来代替目标实例,如果BeanPostProcessors 返回代理对象则直接方法返回,否则继续执行后面的doCreateBean方法,而doCreateBean才是真正的实例化方法
      // Give BeanPostProcessors a chance to return a proxy instead of the target bean instance.
      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;
}

注意我注释的resolveBeforeInstantiation方法,给BeanPostProcessors 一个机会来返回一个代理对象来代替目标实例,如果BeanPostProcessors 返回代理对象则直接方法返回,否则继续执行后面的doCreateBean方法,而doCreateBean才是真正的实例化方法。

我们知道,在doCreateBean方法里面会经过实例化,属性赋值等一系列行为,即bean的生命周期,其中applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);和applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);两个方法在初始化方法invokeInitMethods(beanName, wrappedBean, mbd);方法前后执行,源码不再贴出,已经在上一文章讲过,这里要注意的是,此处的后置处理器类型为BeanPostProcessor,而我们之前注册到容器中的后置处理器类型为InstantiationAwareBeanPostProcessor,二者区别是:
【BeanPostProcessor是在Bean对象创建完成初始化前后调用的】
【InstantiationAwareBeanPostProcessor是在创建Bean实例之前先尝试用后置处理器返回对象的】

那么为什么后者是实例化之前处理放回对象呢?看resolveBeforeInstantiation源码:

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) {
               bean = applyBeanPostProcessorsAfterInitialization(bean, beanName);
            }
         }
      }
      mbd.beforeInstantiationResolved = (bean != null);
   }
   return bean;
}

可以看到先调用applyBeanPostProcessorsBeforeInstantiation(targetType, beanName);方法返回bean,如果bean不为null,继续调用applyBeanPostProcessorsAfterInitialization(bean, beanName);方法,看applyBeanPostProcessorsBeforeInstantiation源码:获得所有的后置处理器,如果是InstantiationAwareBeanPostProcessor(BeanPostProcessor的子类)类型,则调用postProcessBeforeInstantiation方法,注意postProcessBeforeInstantiation与BeanPostProcessor类型处理器的postProcessBeforeInitialization名称是不一样的,前者是实例化之前,后者是初始化前后

protected Object applyBeanPostProcessorsBeforeInstantiation(Class<?> beanClass, String beanName) {
   for (BeanPostProcessor bp : getBeanPostProcessors()) {
      if (bp instanceof InstantiationAwareBeanPostProcessor) {
         InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
         Object result = ibp.postProcessBeforeInstantiation(beanClass, beanName);
         if (result != null) {
            return result;
         }
      }
   }
   return null;
}

如此,任何bean的实例化之前都会调用AbstractAutoProxyCreator的postProcessBeforeInstantiation方法来返回一个代理对象

postProcessBeforeInstantiation和postProcessAfterInitialization详解

我们先按顺序看postProcessBeforeInstantiation的源码

public Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) throws BeansException {
   Object cacheKey = getCacheKey(beanClass, beanName);

   if (beanName == null || !this.targetSourcedBeans.contains(beanName)) {
      if (this.advisedBeans.containsKey(cacheKey)) {
         return null;
      }
      if (isInfrastructureClass(beanClass) || shouldSkip(beanClass, beanName)) {
         this.advisedBeans.put(cacheKey, Boolean.FALSE);
         return null;
      }
   }

   // Create proxy here if we have a custom TargetSource.
   // Suppresses unnecessary default instantiation of the target bean:
   // The TargetSource will handle target instances in a custom fashion.
   if (beanName != null) {
      TargetSource targetSource = getCustomTargetSource(beanClass, beanName);
      if (targetSource != null) {
         this.targetSourcedBeans.add(beanName);
         Object[] specificInterceptors = getAdvicesAndAdvisorsForBean(beanClass, beanName, targetSource);
         Object proxy = createProxy(beanClass, beanName, specificInterceptors, targetSource);
         this.proxyTypes.put(cacheKey, proxy.getClass());
         return proxy;
      }
   }

   return null;
}

以我们的业务类calculator为例,先从缓存中获得key值即beanName,用于判断是否需要创建代理,,判断条件为如果是基础类或者需要跳过就直接返回null,先看isInfrastructureClass方法:

protected boolean isInfrastructureClass(Class<?> beanClass) {
   boolean retVal = Advice.class.isAssignableFrom(beanClass) ||
         Pointcut.class.isAssignableFrom(beanClass) ||
         Advisor.class.isAssignableFrom(beanClass) ||
         AopInfrastructureBean.class.isAssignableFrom(beanClass);
   if (retVal && logger.isTraceEnabled()) {
      logger.trace("Did not attempt to auto-proxy infrastructure class [" + beanClass.getName() + "]");
   }
   return retVal;
}

表示如果传进来得class是Advice、Pointcut、Advisor、AopInfrastructureBean则返回true,不需创建代理,显然此处返回false,然后看shouldSkip方法:

protected boolean shouldSkip(Class<?> beanClass, String beanName) {
   return false;

可以看到方法直接为放回false

接下来如果当前类拥有自定义的TargetSource才会创建代理,所以此处仍没有创建代理

// Create proxy here if we have a custom TargetSource.
// Suppresses unnecessary default instantiation of the target bean:
// The TargetSource will handle target instances in a custom fashion.
if (beanName != null) {
   TargetSource targetSource = getCustomTargetSource(beanClass, beanName);
   if (targetSource != null) {
      this.targetSourcedBeans.add(beanName);
      Object[] specificInterceptors = getAdvicesAndAdvisorsForBean(beanClass, beanName, targetSource);
      Object proxy = createProxy(beanClass, beanName, specificInterceptors, targetSource);
      this.proxyTypes.put(cacheKey, proxy.getClass());
      return proxy;
   }
}

接下来创建bean,然后在bean实例化后并初始化之后,会调用applyBeanPostProcessorsAfterInitialization方法,然后调用AbstractAutoProxyCreator的postProcessAfterInitialization方法

public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
   if (bean != null) {
      Object cacheKey = getCacheKey(bean.getClass(), beanName);
      if (!this.earlyProxyReferences.contains(cacheKey)) {
         return wrapIfNecessary(bean, beanName, cacheKey);
      }
   }
   return bean;
}

此方法会判断bean有没有被代理过,如果没有,判断是否需要代理

protected Object wrapIfNecessary(Object bean, String beanName, Object cacheKey) {
   if (beanName != null && this.targetSourcedBeans.contains(beanName)) {
      return bean;
   }
   if (Boolean.FALSE.equals(this.advisedBeans.get(cacheKey))) {
      return bean;
   }
   if (isInfrastructureClass(bean.getClass()) || shouldSkip(bean.getClass(), beanName)) {
      this.advisedBeans.put(cacheKey, Boolean.FALSE);
      return bean;
   }
	
   // Create proxy if we have advice.
   Object[] specificInterceptors = getAdvicesAndAdvisorsForBean(bean.getClass(), beanName, null);
   if (specificInterceptors != DO_NOT_PROXY) {
      this.advisedBeans.put(cacheKey, Boolean.TRUE);
      Object proxy = createProxy(
            bean.getClass(), beanName, specificInterceptors, new SingletonTargetSource(bean));
      this.proxyTypes.put(cacheKey, proxy.getClass());
      return proxy;
   }

   this.advisedBeans.put(cacheKey, Boolean.FALSE);
   return bean;
}

如果有资格被代理,即specificInterceptors 不为空,这里是获得当前bean的可用通知方法,此处我们写了五个,getAdvicesAndAdvisorsForBean方法最终会调用findEligibleAdvisors方法获得所有可以应用到当前bean身上的增强即通知,然后进行排序

protected List<Advisor> findEligibleAdvisors(Class<?> beanClass, String beanName) {
   List<Advisor> candidateAdvisors = findCandidateAdvisors();
   List<Advisor> eligibleAdvisors = findAdvisorsThatCanApply(candidateAdvisors, beanClass, beanName);
   extendAdvisors(eligibleAdvisors);
   if (!eligibleAdvisors.isEmpty()) {
   	//排除
      eligibleAdvisors = sortAdvisors(eligibleAdvisors);
   }
   return eligibleAdvisors;
}

获得资格,继续调用createProxy方法创建代理,继而调用proxyFactory.getProxy方法

@Override
public AopProxy createAopProxy(AdvisedSupport config) throws AopConfigException {
   if (config.isOptimize() || config.isProxyTargetClass() || hasNoUserSuppliedProxyInterfaces(config)) {
      Class<?> targetClass = config.getTargetClass();
      if (targetClass == null) {
         throw new AopConfigException("TargetSource cannot determine target class: " +
               "Either an interface or a target is required for proxy creation.");
      }
      if (targetClass.isInterface() || Proxy.isProxyClass(targetClass)) {
         return new JdkDynamicAopProxy(config);
      }
      return new ObjenesisCglibAopProxy(config);
   }
   else {
      return new JdkDynamicAopProxy(config);
   }
}

可以发现如果当前bean实现了接口,则创建jdk动态代理,否则返回一个cglib动态代理

总结

1、 @EnableAspectJAutoProxy注解给容器中注册一个AnnotationAwareAspectJAutoProxyCreator;
2、 AnnotationAwareAspectJAutoProxyCreator的继承体系中通过后置处理器和initBeanFactory等方法影响后续创建的bean的生命周期,因为配置类的refresh()方法是先注册后置处理器,再处理剩下的bean
3、 AnnotationAwareAspectJAutoProxyCreator的作用:
1)每一个bean创建之前,调用postProcessBeforeInstantiation();
2)创建对象
3)初始化对象之后调用postProcessAfterInitialization


本文链接: http://www.dtmao.cc/news_show_350360.shtml

附件下载

相关教程

    暂无相关的数据...

共有条评论 网友评论

验证码: 看不清楚?