0

I noticed that I made a circular dependency injection. The weird thing is I did not get any errors at runtime. But when I'm debugging the code I see that there is an infinite injection.

Let me quote interfaces and their implementations.

public interface AService {
    //methods here
}

..

public interface BService {
    //methods here
}

..

@Service
class AServiceImpl implements AService {

    @Autowired
    private BService bService; 
}

..

@Service
class BServiceImpl implements BService {

    @Autowired
    private XService xService;
}

..

@Service
class XService {

 @Autowired
 private AService aService;
}

As you see above; AService -> BService -> XService -> AService

I did not get any circular dependency exception during run time. But when I put watchpoint on AService in XService I see that there is an infinite loop between above flow.

When I see that I categorized this as a bad design. With using @Lazy annotation it's fixed but anyway I did not understand how I don't get circular dependency injection exception. Is it because I'm using interfaces and hiding implementations?

Thank you.

memoricab
  • 425
  • 1
  • 7
  • 28
  • Try injecting `XService` into a very separate Class – Alex Andrade Feb 07 '20 at 22:16
  • https://stackoverflow.com/questions/3485347/circular-dependency-in-spring and https://www.baeldung.com/circular-dependencies-in-spring – Ivan Feb 07 '20 at 22:29
  • "The beans are instantiated first, then injected into each other." @Richard Fearn So I did nothing neither constructor injection nor setter method. Just autowired the circular dependencies and Spring resolved it? Want to get your attention again that I injected dependencies as classical way with Autowired and somehow Spring resolved circular injection; however I can see during debugging that dependencies are going infinite but there is no any exceptions. – memoricab Feb 07 '20 at 22:37
  • Ok, now I learnt a thing that there is no need for setter method if we autowire dependency field. So I guess with autowired field spring still resolves the circular dependency exception – memoricab Feb 07 '20 at 22:47

0 Answers0