I'm with a JEE application based on Servlets and EJB 3.1. I want to inject the EJBs by annotation. From the Servlet itself I can do it, but if I do it through another class (a Controller) it does not inject it. Let me explain by example:
I have the following EJB
@Local
public interface StackOverflowSession {
String formularPregunta(String idPregunta);
}
@Stateless
public class StackOverflowSessionBean extends BaseSession implements StackOverflowSession {
...
}
And then the Servlet, from which, through the annotation @EJB
, it injects me without problem and I can access its methods:
public class StackOverflowServlet extends ServletBase<Pregunta> {
@EJB
StackOverflowSession stackOverflowSession;
@Override
protected void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String idPregunta = request.getParameter("idPregunta");
String pregunta = stackOverflowSession.formularPregunta(idPregunta);
}
}
However, if instead of doing it directly, I make an intermediate class Controller to do this task:
public class StackOverflowController {
@EJB
StackOverflowSession stackOverflowSession;
public String formularPregunta(final String idPregunta) {
return stackOverflowSession.formularPregunta(idPregunta);
}
}
And from the Servlet I use it:
public class StackOverflowServlet extends ServletBase<Pregunta> {
StackOverflowController stackOverflowController;
@Override
public void init(ServletConfig config) throws ServletException {
super.init();
stackOverflowController = new StackOverflowController();
}
@Override
protected void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String idPregunta = request.getParameter("idPregunta");
String pregunta = stackOverFlowController.formularPregunta(idPregunta);
}
}
In this way, stackOverflowSession
in StackOverflowController
is not initialized, and gives its corresponding NullPointer
.
Could someone explain to me why this behavior?
Thank you very much, best regards.