Injecting a stateless EJB into Servlet

blaine picture blaine · Mar 27, 2013 · Viewed 7.4k times · Source

I'm trying to inject a stateless EJB into servlet. But it is not working. Did I understand something wrong? If I do this in a @WebService annotated class, I can use the injected EJB without problems.

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 causes a NullPointerException. I tried to do a 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

Answer

BalusC picture BalusC · Mar 27, 2013

You're trying to access it in the constructor. The injected dependencies are not available in the constructor. It's not possible to set an instance variable if the instance is not constructed yet. You're basically expecting it to work like this:

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

This is clearly not the case. You can access it at earliest in init() method of the servlet. It's also just available in any of the doXxx() methods of the servlet.

To start, replace

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

by

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

Unrelated to the concrete problem, I strongly recommend to work on your Java naming conventions. The lowercased and underscored class names are not conform standard Java naming conventions, which slowdowns the interpreting of the code by seasoned Java developers.