Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialize a circular dependency (final fields referencing each other)?

How do you initialize this:

class A {
    final B b;

    A(B b) {
        this.b = b;
    }
}

class B {
    final A a;

    B(A a) {
        this.a = a;
    }
}

DI framework, reflection, better design?

Motivation and a use case (added):

My particular use case is simplifying field access in A's and B's sub-classes. So I'm injecting them to shortly reference them by fields in the derived classes without a need to declare explicitly in each sub-class.

There is also a recommendation on DI that objects should better be immutable: Guice best practices and anti-patterns.

like image 306
Andrey Chaschev Avatar asked Nov 06 '13 09:11

Andrey Chaschev


People also ask

How do you correct circular dependency?

A cyclic dependency is an indication of a design or modeling problem in your software. Although you can construct your object graph by using property injection, you will ignore the root cause and add another problem: property injection causes Temporal Coupling. Instead, the solution is to look at the design closely.

How do I fix circular dependency in react?

This circular relationship caused a problem and webpack could not resolve the dependencies correctly. Our solution was to upgrade our modules to use ES6 import/exports. This enabled us to reuse the react components and avoid circular dependencies while moving us closer to ES standards.

How do I resolve circular dependencies in Spring?

A simple way to break the cycle is by telling Spring to initialize one of the beans lazily. So, instead of fully initializing the bean, it will create a proxy to inject it into the other bean. The injected bean will only be fully created when it's first needed.


1 Answers

You could use a factory method

class A {
    final B b;

    A(B b) {
        this.b = b;
    }
}

abstract class B {
    final A a;

    B() {
        this.a = constructA();
    }

    protected abstract A constructA();
}

public class C {
    public static void main(String []args){
        new B(){
            protected A constructA(){
                return new A(this);
            }
        };
    }
}
like image 199
Matthew Mcveigh Avatar answered Oct 16 '22 05:10

Matthew Mcveigh