Home  >  Article  >  Java  >  How to Inject Stateless EJBs into JAX-RS Web Services?

How to Inject Stateless EJBs into JAX-RS Web Services?

Susan Sarandon
Susan SarandonOriginal
2024-11-07 11:48:03433browse

How to Inject Stateless EJBs into JAX-RS Web Services?

Injecting EJBs into JAX-RS Web Services

Issue Description:

In an attempt to inject a Stateless EJB into a JAX-RS web service using annotations, the EJB instance remains null in the service class, resulting in a NullPointerException upon use.

Environment Details:

  • Glassfish 3.1
  • Netbeans 6.9 RC 2
  • Java EE 6

Solution Options:

Option 1: Inject using the Injection Provider SPI

  • Implement a custom injection provider that performs the EJB lookup and injection.
  • For example, in Jersey 1.17:
import com.sun.jersey.core.spi.component.ComponentContext;
import ...
public class EJBProvider implements InjectableProvider<EJB, Type> {
    // Implementation details...
}

Option 2: Convert the Resource Class to an EJB

  • Make the JAX-RS resource class a Stateless EJB itself, allowing it to manage its own dependencies.

Option 3: Leverage CDI

  • Use Context and Dependency Injection (CDI) to inject the EJB into the JAX-RS resource class.

Example:

@Path("book")
@RequestScoped
public class BookResource {
    @Inject
    private BookEJB bookEJB;
    // Implementation details...
}

Additional Resources:

  • [EJB Injection](https://docs.oracle.com/javaee/7/api/javax/ejb/EJB.html)
  • [@EJB Injection](https://stackoverflow.com/questions/1130846/ejb-injection)
  • [Combining REST Services with EJB 3.1](https://dzone.com/articles/combining-rest-services-with-ejb-31)
  • [EJB 3.1 and REST - The Lightweight Hybrid](https://weblogs.java.net/blog/emcfarlane/archive/2009/12/10/ejb-31-and-rest-lightweight-hybrid)
  • [Injecting an EJB from a jar into a jax-rs class in a war](https://stackoverflow.com/questions/6474811/injecting-an-ejb-from-a-jar-into-a-jax-rs-class-in-a-war)

The above is the detailed content of How to Inject Stateless EJBs into JAX-RS Web Services?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn