Spring 使用@Async出现循环依赖Bean报错的解决方案

初现端倪

Caused by:org.springframework.beans.factory.BeanCurrentlyInCreationException: Errorcreating bean with name 'asyncUpdate': Bean with name 'asyncUpdate' has beeninjected into other beans [dealerService,userService] in its raw version aspart of a circular reference, but has eventually been wrapped. This means thatsaid other beans do not use the final version of the bean. This is often theresult of over-eager type matching - consider using 'getBeanNamesOfType' withthe 'allowEagerInit' flag turned off, for example.
以上这一长串大概的意思就是说,'asyncUpdate' bean已经注入了一个版本,程序中出现了循环依赖的可能性。
就如:在创建A类时,构造器需要B类,那将去创建B,在创建B类时又发现需要C类,则又去创建C,最终在创建C时发现又需要A,从而形成一个环,没办法创建。

分析问题

首先来看看这里的AsyncUpdate类是用来做什么的:

@Component
@EnableAsync
public classAsyncUpdate {
 
   @Autowired
   private DealerMemberMapper dealerMemberMapper;
 
   @Autowired
   private UserService userService;
 
   @Autowired
   private GoodsSubscribeService goodsSubscribeService;
 
   /**
    *异步更新
    */
   @Async
   public void updateDealerAsync(Dealer  dealer, String mobilephone, Integer type) throwsException {
       //篇幅有限就不贴代码
   }
}

@Async注解:表示当前是一个异步方法。
@Component:表示把普通pojo实例化到spring容器中,相当于配置文件中的
@EnableAsync注解:表示开启异步线程。

@Service
public classDealerService {
 
   @Autowired
   private DealerMapper dealerMapper;
 
   @Autowired
   private UserService userService;
 
   @Autowired
   private AsyncUpdate asyncUpdate;
 
   //一些代码
}
 

通过以上两段程序能够得到,问题出现的原因:简单的讲就是在启动程序的时候,Spring已经对DealerService里的asyncUpdate、userService加载完成,当准备创建AsyncUpdate类的时候发现使用了@Async注解,即spring又需将该Bean代理一次,然后Spring发现该Bean已经被其他对象注入,这里就是问题的关键所在了。

即:在创建A类时,构造器需要B类,那将去创建B,在创建B类时又发现需要C类,则又去创建C,最终在创建C时发现又需要A,从而形成一个环,没办法创建

解决方案

大量查找解决方案后发现解决方案有三:

1.使用 @Lazy 或者 @ComponentScan(lazyInit = true) 来解决该问题,经过我实验,@Lazy必须和@Autowired联合使用才能生效,单纯在类上添加 @Lazy 并无意义。

@Autowired
@Lazy
private AsyncUpdate asyncUpdate;
 
  1. 使用基于 Setter 的注入
@Component
public classDealerService {
 
    private AsyncUpdate a;
 
    public void setA(AsyncUpdate a) {
        this.a = a;
    }
}
 
 
 
@Component
public classAsyncUpdate {
 
    private DealerService ds;
 
    public void setDs(DealerService ds) {
        this.ds = ds;
    }
}

3.使用@Autowired注解防止循环注入,如:

@Component
public classDealerService {
 
    @Autowired
    private AsyncUpdate a;
} 
 
@Component
public classAsyncUpdate {
 
    private DealerService ds;
 
    @Autowired
    public void foo(DealerService ds) {
        this.ds= ds;
    }
}

注:当@Autowired 对方法或构造函数进行标注时,表示如果构造函数有两个入参,分别是 bean1 和bean2,@Autowired 将分别寻找和它们类型匹配的 Bean,将它们作为 baanService (Bean1 bean1 ,Bean2 bean2) 的入参来创建baanService Bean。

posted @ 2019-06-30 13:42  静月亭№  阅读(2222)  评论(0编辑  收藏  举报