简体   繁体   English

具有循环依赖的HK2注射

[英]HK2 Injection With Circular Dependency

I am using HK2 as dependency injection framework. 我正在使用HK2作为依赖项注入框架。 I am instantiating a State Machine inside my application. 我正在我的应用程序中实例化一个状态机。 So, A <-> B is quite possible because depending on the input, one can transition back to A from B. 因此,A <-> B是很有可能的,因为取决于输入,一个人可以从B过渡回A。

@Singleton 
class StateManager extends SomeInterface{

    @Inject
    private B b;

    @Inject
    private A a;
}

@Singleton 
class A extends State{

    @Inject
    private B b;

    @Inject
    private StateManager sm;

}

@Singleton 
class B extends State{

    @Inject
    private A a;

    @Inject
    private StateManager sm;
}

How can I achieve something like this? 我怎样才能实现这样的目标? Above example is just for illustration. 以上示例仅用于说明。 I have more states than this. 我的州比这更多。 I tried to see if it is a duplicate but couldn't find one that deals with. 我试图查看它是否重复,但是找不到可以处理的重复项。 When I try to ServiceLocator.getService(StateManager.class) to get this graph, I get circular dependency exception. 当我尝试使用ServiceLocator.getService(StateManager.class)获取此图时,出现循环依赖异常。 What is the better of doing such things? 做这样的事情有什么好处?

You should be able to to inject javax.inject.Provider<B> . 您应该能够注入javax.inject.Provider<B> From the Javadoc 从Javadoc

Provides instances of T . 提供T实例。 Typically implemented by an injector. 通常由喷射器实现。 For any type T that can be injected, you can also inject Provider<T> . 对于任何可以注入的T类型,还可以注入Provider<T> Compared to injecting T directly, injecting Provider<T> enables: 与直接注入T相比,注入Provider<T>使:

  • retrieving multiple instances. 检索多个实例。
  • lazy or optional retrieval of an instance. 实例的惰性或可选检索。
  • breaking circular dependencies. 打破循环依赖。
  • abstracting scope so you can look up an instance in a smaller scope from an instance in a containing scope. 抽象作用域,以便您可以从包含作用域的实例中查找范围较小的实例。

Then just call get() when you need it 然后在需要时调用get()

B b = bProvider.get();

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

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