CDI injection loop

三世轮回 提交于 2019-11-30 21:48:00
Nick

Circular dependency injection is not required by the CDI standard, unless at least one bean in the cycle has a normal scope. The easiest solution to this is to give A or B a normal scope. If you can't give either a normal scope (from the code mock-up, it looks like they all have the default @Dependent pseudo-scope), you will have to look for other solutions. Posting a real code sample might let us help you with a particular solution, but here is a start:

  • Can A and B be combined into the same class?
  • Can a new class, C, be extracted from A and B, so that both A and B @Inject C instead of each other?

Here are some SO links with other solutions that you might find helpful:

MVP with CDI; avoiding circular dependency

https://stackoverflow.com/questions/14044538/how-to-avoid-cdi-circular-dependency

I solved the problem by using javax.inject.Provider explicitly. Although I feel like this should be done under the hood by WELD automatically this was not the case for me too. This worked for me and solved my related problem.

class A {
    @Inject
    Provider<B> b; // access with b.get()
}

class B {
    @Inject
    Provider<A> a; // access with a.get()
}

I haven't tested it, but it could be enough to use one Provider to break the cycle, i.e. you don't need to use it in both classes.

You should inject an Instance<B> instead of B (and/or Instance<A> instead of A)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!