Injecting a stateless EJB into Servlet

有些话、适合烂在心里 提交于 2019-12-10 15:11:19

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/15666572/injecting-a-stateless-ejb-into-servlet

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!