Tobia
Tobia

Reputation: 9506

Why @Async annotation causes circular reference issue?

This is my bean:

@Service
public class MyService{

   @Autowire
   private OtherService service;

   @Async
   public jobAync(){
      job();
   }
   public job(){
      ...
   }
}

I cannot understand why @Async annotation to jobAync causes Circular Reference Problem to Spring, if I remove that annotation everything works... I expect to find problems in autowires but seems to be linked to @Async.

Upvotes: 7

Views: 2549

Answers (2)

Yusuf
Yusuf

Reputation: 337

Hi here is why @async cause circular reference error:

AsyncConfigurer configuration classes get initialized early in the application context bootstrap. If you need any dependencies on other beans there, make sure to declare them 'lazy' as far as possible in order to let them go through other post-processors as well.

https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/scheduling/annotation/EnableAsync.html

You can add @lazy to the injection point of this bean in the other beans.

Upvotes: 2

Tobia
Tobia

Reputation: 9506

I don't know if it is the best solution but I solved with two different services, the main one and the async one:

@Service
public class MyService{

   @Autowire
   private OtherService service;

   public job(){
      ...
   }
}

@Service
public class MyServiceAsync{

   @Autowire
   private MyService myService;

   @Async
   public job(){
      myService.job();
   }
}

Upvotes: 0

Related Questions