Inject EJB into controller

2

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.

    
asked by Dani 28.06.2018 в 15:08
source

1 answer

2

Managed objects ( managed beans ) are injected by the container (CDI, JSF) when it is the container that creates the objects .

Here is your code that creates an instance of StackOverflowController

  

stackOverflowController = new StackOverflowController ();

so it does not inject anything.

You have to make StackOverflowController be a managed object, with the appropriate annotation to the framework you use, and have it injected in servlet , eg

@Inject
private StackOverflowController stackOverflowController;
    
answered by 28.06.2018 / 15:15
source