4

If we have statless bean then it can be injected into Servlet by @EJB annotation. For example:

@Stateless
public class LongTimeService {  
    public void do() {
        //logic
    }
}

public class ServletWithBean extends HttpServlet {  
    @EJB
    private LongTimeService bean;

    @Override
    public void service(ServletRequest arg0, ServletResponse arg1)
        throws ServletException, IOException {
             bean.do;
             ...
    }
}

In this case we will have only one instance of LongTimeService bean during all lifecycle of Servlet. From ejb container perspective when web container will construct Servlet with bean it ask instance from ejb container and will keep this instance until servlet will be destroed and every servlet request will work only with one instance. I think this is bad way to use Statless EJB because th don't create for such kind of usage. For this perpes for example useful @Singleton statfull bean. But if we want use statless bean then we can lookup instance of this bean from the Context every time inside of the method.

public class ServletWithBean extends HttpServlet {

    @Override
    public void service(ServletRequest arg0, ServletResponse arg1)
        throws ServletException, IOException {
        Context ctx = new InitialContext();
        LongTimeService bean =  context.lookup("LongTimeService");
             bean.do;
             ...
    }
}

Is it correct and possible to use this approach?

Alstresh
  • 583
  • 2
  • 4
  • 16

1 Answers1

4

From ejb container perspective when web container will construct Servlet with bean it ask instance from ejb container and will keep this instance until servlet will be destroed and every servlet request will work only with one instance.

Your reasoning is right, however, the instance that is injected into the servlet class member is actually an instance of an object called Stub or Proxy, it is not really an EJB instance.

Basically, every time you invoke an ejb´s method from your servlet, the Stub asks the ejb container a reference to an ejb, the container will get an available ejb from the pool, this ejb will process the request and once the job is done it will come back to the pool.

Therefore, if your servlet processes several requests at the same time, the stub will get a different ejb reference per request.

Notes that the stub object implementation needs to be thread-safe (and for Stateless bean it is).

I think this is bad way to use Statless EJB because th don't create for such kind of usage.

According to the above points, yes, you can use @EJB injection from a servlet.

About lookup stub approach:

It also can work (you will get an Stub per request), but it is not necessary for stateless and it has an important drawback: the lookup is a time-consuming operation, therefore, you will gain a latency in your service time response without compensation.

I hope this help you.

Gabriel Aramburu
  • 2,951
  • 2
  • 16
  • 20