Circular Dependency in Java Constructors

Circular dependency in Java constructors

The constructor of your class A calls the constructor of class B. The constructor of class B calls the constructor of class A. You have an infinite recursion call, that's why you end up having a StackOverflowError.

Java supports having circular dependencies between classes, the problem here is only related to constructors calling each others.

You can try with something like:

A a = new A();
B b = new B();

a.setB(b);
b.setA(a);

circular dependency in web application using spring boot security

you can write one line in your application.properties file to remove this error.

spring.main.allow-circular-references= true

Breaking cyclic dependency in constructor

Use setter for passing GameMap into Cell not constructor. You can make it package-protected to hide it from other code and call setter in GameMap constructor or in another loop in GameMapBuilder. All known DE-frameworks use setters to solve circular dependencies.

Field based and Constructor based Circular dependency in Spring boot

In the second example you have the constructor injection, so in case of circular dependency it should fail.
In the first example you use autowiring so dependencies will be injected when they are needed and not on the context loading.

More details here: https://www.baeldung.com/circular-dependencies-in-spring



Related Topics



Leave a reply



Submit