Search code examples
ejbejb-3.0

circular ejb dependencies: what does the spec say?


I know from experience that injection of circular dependencies in EJB do work, at least in some application servers.

I've done it multiple times with self-injection (e.g. to get an EJB proxy for @TransactionAttribute, @RolesAllowed, @Asynchronous etc. to work).

I've done it with more complex graphs too (A->B->A etc.), which obviously work too.

I've done it at least in Glassfish 3/4, Weblogic, and JBoss 7.3. Maybe Weblogic, not sure.

Now, I've been trying to find some precise guarantee from the specification, without success. There are provisions for this in CDI, but I couldn't find any explanation on why it works for EJBs. Is there some indirect one, maybe?

I'm looking from some references from EJB specifications regarding this.


Solution

  • I don't believe the EJB specification explicitly disallows self-injection, which means it implicitly allows it since there is no reason for the bean's own interface to be different from the interface of some other EJB. In practice, self-injection can only work for stateless (and singleton in EJB 3.1) and not stateful since each lookup/injection of a stateful bean creates a new instance, which would result in infinite recusion. For stateful, you can inject SessionContext and use the getter methods to return a "self-proxy" rather than using injection. This technique also works for stateless/singleton, and it might be marginally faster than using injection (particularly if you cache the result in an instance field the same as injection) since the EJB container can probably return a self-proxy more directly than going through injection/JNDI.

    The only additional authority I can give to this answer is that I was one of the primary developers/maintainers of the EJB container in WebSphere Application Server for 5 years. To add to your list of products, I know that self-injection also works in practice on WebSphere Application Server.