Home > Java > javaTutorial > body text

How to Inject EJBs into JAX-RS Services?

DDD
Release: 2024-11-07 07:20:02
Original
313 people have browsed it

How to Inject EJBs into JAX-RS Services?

Injecting EJBs into JAX-RS Services

Problem Description

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.

Solution

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.

Working Example (Option 1)

@Path("book")
public class BookResource {

    @Inject
    private BookEJB bookEJB;

    //...
}
Copy after login
// EJBProvider.java

@Provider
public class EJBProvider implements InjectableProvider<EJB, Type> {
    // ... (Implementation as provided in the answer)
}
Copy after login

Conclusion

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!