Implementing Muteless EJB in a Servlet

I am trying to inject a mute EJB into a servlet. But that does not work. Am I misunderstood something? If I do this in the @WebService class annotated, I can easily use the entered EJB.

My EJB:

 @Stateless public class doSomethingService { public void doSomething() { System.out.println("DO SOMETHING"); } } 

My servlet:

 @WebServlet("/testservlet") public class test_servlet extends HttpServlet { private static final long serialVersionUID = 1L; @Inject private doSomethingService injBean; public test_servlet() { super(); injBean.doSomething(); } 

This raises a NullPointerException . I tried to do JNDI-Lookup, and it worked very well. Is it a fact that @Inject does not work in servlets?

Im using Glassfish 3.1.2.2

+5
servlets cdi ejb inject
source share
1 answer

You are trying to access it in the constructor. The introduced dependencies are not available in the constructor. It is not possible to set an instance variable if the instance is not yet constructed. You basically expect it to work as follows:

 test_servlet servlet; servlet.injBean = new doSomethingService(); servlet = new test_servlet(); 

This is clearly not the case. You can access it as early as possible in the servlet's init() method. It is also available only in any of the servlet's doXxx() methods.

To start, replace

 public test_servlet() { super(); injBean.doSomething(); } 

by

 @Override public void init() { injBean.doSomething(); } 

Not tied to a specific problem, I highly recommend working on Java naming conventions . Class names with lower and lower digits do not comply with standard Java naming conventions, which slows down the interpretation of code by experienced Java developers.

+10
source share

All Articles