I am a newbie to EJB 3 (Also, I Have not worked in EJB 1/2 and have only limited bookish knowledge). I have some experience in web development (JSP/Servlet).I am preparing for SCBCD (and trying to learn EJB in the process) and have started reading EJB 3 in Action book + trying out samples provided. I have few basic questions (Sorry if some of them are too silly)
1. How is a non-HTTP client tracked in terms of accessing a stateful session bean? I understand that HTTP clients are tracked by using the HttpSession's sessionId. But what if the client is a Java SE application? (If IP address is used to reconcile a client - what if there are multiple clients behind the same firewall?)
2. Dependency Injection - The book has a number of examples wherein an EJB reference is injected using @EJB annotation into a Servlet. As a Servlet is multi-threaded, will this not potentially cause multiple threads to access the same EJB reference? Does the container ensure that a different "EJB reference" is used for different threads? (i.e will the container call a setxxx method on the Servlet before calling the doPost/doGet method on every call or is the setxxx method only once after initialization?)
1. There's no need for ids like the http session id. The client has to get a stateful session bean and retain its reference all along the conversation. As long as the client keeps the reference of the bean, it can invoke the bean's methods statefully. The bean will be discarded if the client calls remove() or if the bean times out.
2. Only stateless beans should be injected in a servlet instance variable, because the state of a stateful bean would get unpredictable. There should not be any problem to invoke a stateless session bean. The container will take care of thread safety.
Thanks for your reply. Could you please throw some more details on the points:
1. Stateful bean - (I am interested in knowing the communication/protocol apart from the programming nuances) How does the handshake happen with the EJB reference? All objects are passed by value (through serialization). How does the container know which client has invoked the EJB i.e what token is used to identify the client? Do the stubs generate some kind of unique id?
2. If I understand it clear, it seems that the container would first call the setEJB method before invoking doPost/doGet.
Regarding injecting an EJB into a servlet:
If you inject a session bean (stateful or stateless) into a servlet, it is the responsibility of the EJB container to serialize method calls that are to one and the same instance. In this context serialize means the opposite to parallel.
It is allowed, but perhaps not best practice, to inject a stateful session bean into a servlet - see the reference!
Reference: EJB 3.1 Specification, section 4.3.14.
Finally: Yes, dependency injection always takes place before the EJB is taken into use.