使用@Async导致BeanCurrentlyInCreatio

2020-05-20  本文已影响0人  挡不住的柳Willow

场景描述:

springboot项目启动的时候报错:

org.springframework.beans.factory.BeanCurrentlyInCreationException: 
Error creating bean with name 'messageService': Bean with name 
'messageService' has been injected into other beans [taskService]
 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.

乍一看觉得是循环引用的问题,但是之前只知道spring对单例的循环引用是做了处理的,prototype的情况除外。而该项目中的bean全部是默认的singleton,因此排除prototype。

google一下得知是@Async导致的,官方的解决方式是在 @Async所在的类中添加@Lazy注解 ,本文的目的则是在于剖析为什么使用@Async会导致BeanCurrentlyInCreationException,以及为什么可以用@Lazy来解决问题

场景复现:

1、首先项目需要打开spring的异步开关,在application主类上加@EnableAsync
2、创建一个包含了@Async方法的异步类MessageService

@Service
public class MessageService {
    @Resource    
    private TaskService taskService;   
 
    @Async    
    public void send(){
        taskService.shit();    
    }
}

3、创建另一个正常类TaskService,与异步类形成循环引用的关系(注意MessageServiceTaskService在同一个包内,并且order为默认,因此会先扫描MessageService再扫描TaskService):

@Service
public class TaskService {
    @Resource    
    private MessageService messageService;  
  
    public void shit(){
        System.out.println();    }
}

4、启动springboot项目成功报错

问题出现的原因

在分析原因之前,我们需要提前知道两个重要的点:

  1. spring的aop代理(包括@Transactional事务代理),都是在AbstractAutowireCapableBeanFactorypopulateBean方法后的initializeBean当中的applyBeanPostProcessorsAfterInitialization方法里,通过特定的后置处理器里创建代理对象(一般是AnnotationAwareAspectJAutoProxyCreator
  2. 然而1.当中描述的代理过程,是在这个类不涉及到循环引用的情况下才会执行,也就是说满足百分之90的情况,而循环引用的情况会做特殊的处理,即提前创建代理对象。

举个例子:
T类是个包含了@Transactional方法的类,属于需要被代理的对象,并且通过@Resource(或者@Autowired)的方式依赖了A ,A类中也以同样的方式注入了T,并且T类先于A类开始实例化过程,那么简单的实例化流程就是:

出现本文标题中循环引用异常的原因分析

包含了@Async方法的类与@Transactional的类相似,也会被替换成一个新的代理类,但是与普通aop不同的是,@Async不会在 getEarlyBeanReference阶段执行创建代理的逻辑(这么做的原因暂时没仔细分析),而是被延迟到了initializeBean步骤当中(即1.提到的90%的代理情况),这样一来就会导致TaskService注入的并不是最终创建完成的MessageService的代理对象,很明显这样的结果是不合理的,而在代码层面,spring的AbstractAutowireCapableBeanFactory当中,在initializeBean和将bean放入一级缓存之间,有这么一段容易被忽视的代码,用于把控最终的循环引用结果正确性:

//是否允许提前暴露,可以理解为是否允许循环引用
if (earlySingletonExposure) {
    //遍历一到三级缓存,拿到的bean
   Object earlySingletonReference = getSingleton(beanName, false);
    //如果缓存中的对象不为空
   if (earlySingletonReference != null) {
      //exposedObject是执行了initializeBean之后的对象,bean是通过构造器创建的原始对象
        //如果两者相等,则将exposedObject设置为缓存中的对象
      if (exposedObject == bean) {
         exposedObject = earlySingletonReference;
      }   //如果两者不是同一个对象,并且不允许直接注入原生对象(默认false),且当前beanName有被其他的bean所依赖
      else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) {
        //则获取所有依赖了该beanName的对象
         String[] dependentBeans = getDependentBeans(beanName);
         Set<String> actualDependentBeans = new LinkedHashSet<>(dependentBeans.length);
         for (String dependentBean : dependentBeans) {
            //如果这个对象已经处于一级缓存当中,则添加到actualDependentBeans,即依赖该对象的bean是一个走完了整个流程,不会再有机会回炉重做的bean
            if (!removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) {
               actualDependentBeans.add(dependentBean);
            }
         }
        //最后判断actualDependentBeans是否为空,不为空就抛循环引用的异常
         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.");
         }
      }
   }
}

我们结合这段代码来分析@Async循环引用场景:

protected boolean removeSingletonIfCreatedForTypeCheckOnly(String beanName) {
//如果不是已经完全创建好的bean,就返回true,否则返回false
   if (!this.alreadyCreated.contains(beanName)) {
      removeSingleton(beanName);
      return true;
   }
   else {
      return false;
   }
}

这里就要回到场景复现时提到的:

3、注意MessageServiceTaskService在同一个包内,并且order为默认,因此会先扫描MessageService再扫描TaskService

为什么@Lazy可以解决这个问题

@Lazy被大多数人理解为:

当使用到的时候才会加载这个类。

这个也算是spring希望我们看到的,但是这个描述实际上不完全准确。举个例子:

@Service
public class TaskService {
    @Resource    
    @Lazy
    private MessageService messageService;  
  
    public void shit(){
        System.out.println();
    }
}

思考

为什么spring要用这样的方式来处理@Lazy呢?
可能是真的lazy,也是真的聪明吧,这样一来不需要修改整个复杂的bean实例化流程,只需要在注入的时候做一个小小的判断,相比较而言改动很小,影响也很小。

上一篇 下一篇

猜你喜欢

热点阅读