-2

e.g class Employee is dependent on class Student and class Student is dependent on class class Person and class Person is dependent on class Employee

Kishor Gardi
  • 33
  • 1
  • 5
  • Have you checked [this](https://www.baeldung.com/circular-dependencies-in-spring)? – BeUndead Mar 04 '20 at 12:20
  • There are numerous posts online which explain cyclic dependencies in Spring, plus you can check their actual source code. Moreover, there are many similar questions on SE, like this https://stackoverflow.com/questions/3485347/circular-dependency-in-spring – eugen-fried Mar 04 '20 at 12:39
  • Does this answer your question? [Circular dependency in Spring](https://stackoverflow.com/questions/3485347/circular-dependency-in-spring) – eugen-fried Mar 04 '20 at 12:40

1 Answers1

1

Before all : avoid cyclic dependency as much as possible.
That promotes a very high coupling between classes and makes the whole design more complex.

That works in the same way as without Spring.
With a constructor to set the dependency in both classes you are stuck because of cyclic creation :

public Foo(Bar bar){...
}

public Bar(Foo foo){...
}

Bar bar = new Bar(new Foo(???));  // stuck
Foo foo = new Foo(new Bar(???));  // stuck

With a constructor in one side and a setter in the other you can mitigate the creation issue :

Foo class :

public Foo(){...
}
public setBar(Bar bar){...
}

Bar class :

public Bar(Foo foo){...
}

You can so do :

Foo foo = new Foo(); // ok 
Bar bar = new Bar(foo);  // ok
foo.setBar(bar); // ok      

Concretely in Spring, if you use constructor injection in both classes, Spring container startup will fail because that requires to instantiate the class (by reflection) with as arg a bean that doesn't exist.
If you don't use constructor injection in both ways but setter or field injection, Spring will mitigate the situation by doing things in two steps :

- instantiate the beans with the no arg constructor 
- set dependency foo in bar
- set dependency bar in foo
davidxxx
  • 125,838
  • 23
  • 214
  • 215