我使用 HK2 作为依赖注入(inject)框架。我正在我的应用程序中实例化一个状态机。因此,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;
}
我怎样才能实现这样的目标?上面的例子只是为了说明。我有比这更多的状态。我试图查看它是否重复,但找不到可以处理的。当我尝试 ServiceLocator.getService(StateManager.class)
获取此图时,出现循环依赖异常。做这样的事情有什么好处?
最佳答案
您应该能够注入(inject) javax.inject.Provider<B>
.来自 Javadoc
Provides instances of
T
. Typically implemented by an injector. For any typeT
that can be injected, you can also injectProvider<T>
. Compared to injectingT
directly, injectingProvider<T>
enables:
- 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.
然后调用get()
当你需要的时候
B b = bProvider.get();
关于java - 具有循环依赖的 HK2 注入(inject),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31704384/