Today I ran into an interesting problem when trying to inject an EJB into a JAX-RS resource (in GlassFish 4.1, running the preinstalled version of Jersey).
@Stateless
public class MeuEJB implements MinhaInterface {
// código
}
@Path("caminho")
public class MeuRecurso {
@Inject
private MinhaInterface minhaInterface;
// código
}
When trying to access the resource, it received a 500 Internal Server Error
saying that there were no valid candidates for MinhaInterface
injection.
Trying to dig deeper into the subject I discovered that since Jersey version 2.0 it includes an IoC library called HK2 . This container apparently knows nothing a priori about the CDI or EJB scopes.
An obvious alternative is to do the jndi lookup manually. In addition, there are solutions with InjectionManager
and SPI.
That said, the Java EE 7 tutorial gives two recipes to integrate JAX-RS with EJB.
Transform the resource into an EJB:
@Path("caminho")
@Stateless
public class MeuRecurso {
@EJB
private MinhaInterface minhaInterface;
// código
}
Transform the resource into a CDI bean:
@Path("caminho")
@RequestScoped
public class MeuRecurso {
@Inject
private MinhaInterface minhaInterface;
// código
}
Both alternatives work correctly. What I would like to know from an architectural (and practical) point of view is: What are the implications of turning my JAX-RS resource into a Stateless Session Bean or a CDI Managed Bean in>? Have best practices been defined on this front?