Search code examples
dependency-injectioncdicircular-dependencyjboss-weld

CDI injection loop


I'm running into a issue with CDI Injection into a Weld container in JBoss 7.1.1

I've got the following object model :

@Stateless
class ServiceEjb {
@Inject
A a;
}

class A {
@Inject
B b;
}

class B {
@Inject
A a;
}

When trying to inject A or B in my stateless class, injection loop and crash with a javax.enterprise.inject.CreationException.

I try many thing (scoping, @Singleton on A or B but without success). I don't want to break the code, and those injections makes senses.

Any clues will be greatly appreciated.


Solution

  • 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