2787184
2787184

Reputation: 3871

Micronaut Circular dependency

How to resolve circular dependency in micronaut, I am referring to link javax.inject.Inject

A.java

import javax.inject.Inject;
import javax.inject.Provider;
import javax.inject.Singleton;
@Singleton
public class A {
    @Inject
    private Provider<B> b;
}

B.java

import javax.inject.Inject;
import javax.inject.Provider;
import javax.inject.Singleton;
@Singleton
public class B {
    @Inject
    private Provider<A> a;
}

Factory.java

import io.micronaut.context.annotation.Factory;
import javax.inject.Inject;
import javax.inject.Singleton;
@Factory
public class Factory {

    @Inject
    private A a;

    @Inject
    private B b;
}

Exception:

23:22:04.354 [nioEventLoopGroup-1-5] DEBUG i.m.h.s.netty.RoutingInBoundHandler:1357-Encoding emitted response object [Internal Server Error: Failed to inject value for parameter [b] of class: B

Message: Circular dependency detected
Path Taken: 
Factory.a --> new A([B b]) --> new B([A a])
^                                                                                                                                                                                                                                                                                                                 |                                   |
+----------------------------------+] using codec: io.micronaut.jackson.codec.JsonMediaTypeCodec@35a578

Upvotes: 1

Views: 2378

Answers (1)

Michael
Michael

Reputation: 44090

Fundamentally this is probably a problem with your design. If A and B both require references to one another, they are too tightly coupled. They should probably just be one class.

Anyway, the issue is that the framework doesn't know which to create first. It's in a catch 22 situation; it can't create A without, and can't create B without A.

I believe if you inject one of references with a setter then it will mean that you can construct one before the other, but there will be a brief period during initialization where B.a is null. Probably irrelevant.

@Singleton
public class B {
    private Provider<A> a;

    @Inject
    public void setA(Provider<A> a) {
        this.a = a;
    }
}

But fix your design!

Upvotes: 1

Related Questions