Attempting to inject a Stateless EJB into a JAX-RS webservice through annotations results in a null EJB reference, leading to a NullPointerException upon usage.
While annotating the JAX-RS web service as @Stateless may seem like a direct solution, it is not feasible with JAX-RS alone. Consider the following alternative approaches:
Option 1: Injection Provider SPI
Implement an injection provider that performs the lookup and injection of the EJB. Register the provider accordingly.
Option 2: Embed BookResource as an EJB
Annotate the BookResource class as @Stateless and manage its lifecycle within an EJB. However, this approach makes unit testing more challenging.
Option 3: Utilize CDI
Employ CDI for dependency injection, as shown in the provided example. This approach offers simplicity and flexibility, particularly in testing environments.
@Path("book") public class BookResource { @Inject private BookEJB bookEJB; //... }
// EJBProvider.java @Provider public class EJBProvider implements InjectableProvider<EJB, Type> { // ... (Implementation as provided in the answer) }
By implementing an injection provider or adopting CDI, it becomes possible to inject EJBs into JAX-RS services, expanding the integration options between the two frameworks.
The above is the detailed content of How to Inject EJBs into JAX-RS Services?. For more information, please follow other related articles on the PHP Chinese website!