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?