简体   繁体   English

Micronaut循环依赖

[英]Micronaut Circular dependency

How to resolve circular dependency in micronaut, I am referring to link javax.inject.Inject 如何解决Micronaut中的循环依赖关系,我指的是链接javax.inject.Inject

A.java 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 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 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

Fundamentally this is probably a problem with your design. 从根本上讲,这可能是您的设计存在的问题。 If A and B both require references to one another, they are too tightly coupled. 如果AB都需要互相引用,那么它们就太紧密了。 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; 处于22状态。 it can't create A without, and can't create B without A. 没有A就无法创建A,没有A也就无法创建B。

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 Ba is null. 我相信,如果您使用设置器注入引用之一,则意味着您可以先构建一个引用,但是在初始化期间会出现一小段时间,其中Ba为空。 Probably irrelevant. 可能无关紧要。

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

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

But fix your design! 但是,请修改您的设计!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM