7
Today I ran into an interesting problem trying to inject an EJB into a JAX-RS feature (in Glassfish 4.1, running the pre-installed 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 received a 500 Internal Server Error
saying that there were no valid candidates for injection of MinhaInterface
.
Trying to get into it discovered that since version 2.0 of Jersey 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 with SPI.
That said, the very Java EE 7 tutorial gives two recipes to integrate JAX-RS with EJB.
Turn the resource into an EJB:
@Path("caminho") @Stateless public class MeuRecurso { @EJB private MinhaInterface minhaInterface; // código }
Turn the resource into a CDI bean:
@Path("caminho") @RequestScoped public class MeuRecurso { @Inject private MinhaInterface minhaInterface; // código }
Both alternatives work correctly. What I’d 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 in a CDI Managed Bean? Best practices have already been defined on this front?