The @EJB annotation can be use in “managed clients” to access an EJB.
One can place this annotation in a servlet class, declaring a member variable.
public class MyServlet extends HttpServlet {
@EJB
private MyWorkerInterface theWorker;
}
That @EJB annotation is expanded to JNDI lookups that (I assume) are executed when the servlet initialises. Those JNDI lookups might fail: the EJB provider can choose to modify their annotations to specify particular JNDI names, my @EJB reference would then need to specify the non-default JNDI name or the lookup would fail.
Also I guess, as the EJB can be remote there is the possibility of transient, network failures and server-bounce errors.
My thought: when using theWorker, I should check for its validity.
if ( theWorker == null ) {
// ... etc.
My questions:
1.) Are such null checks necessary?
2.) If they are, and the nulls may be caused by a transient error such as a temporary failure of the remote server, is any recovery possible? The servlet is now intialised. Do I really need to restart my servlet in order to recover? Surely not?
3.) Tentative thought: Explicit, lazy, JNDI lookup code may be needed in preference to using @EJB. Comments?
Sorry for not giving any references to specs, I’m only speaking from previous experience with JBoss.
1) No, unless the container made a mistake.
2) Not relevant, your instance will be a proxy to the remote service, implementing the remote interface. The injection will therefore always succeed. The error will arise when you call the methods of the proxy, so you need to be prepared to handle those errors when using the remote interface. That is what RemoteException was intended for, all errors should be wrapped in a RemoteException for you to catch if something goes wrong. If you let it propagate, the tx will be rolled back, which is a sane default if you manipulate tx-enabled resources only.
3) This is usually only needed if you need different initial context properties for the JNDI lookup, but for these cases I would personally use a DI engine and another annotation (@EJBFromHost2 for instance). Using explicit JNDI lookups gets very kludgy, especially if you later want to change to another JNDI implementation or settings (if you want to cluster your app for instance).