-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

3
  • Have you checked this? Commented Mar 4, 2020 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 stackoverflow.com/questions/3485347/… Commented Mar 4, 2020 at 12:39
  • Does this answer your question? Circular dependency in Spring Commented Mar 4, 2020 at 12:40

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.