I read in the book EJB 3 in Action, that use of Dependency Injection (DI) of statefull session beans should be avoided in stateless beans, servlets etc. The reason given is : Injected EJB instances are stored in an instance variable and are available globally for subsequent clients even if a stateless bean instance (of client) is returned to the pool, and an injected stateful bean instance may contain inaccurate state information that will be available to a different client.
Does this mean that the same statefull session bean in injected into various stateless client beans?
Also it has been stated that in such a situation, JNDI is to be used.
As per my understanding, both DI and JNDI do the same task of looking up for the remote interface and returning its reference. Then what difference would it make of using JNDI over DI?
A simple answer to that will be : Your stateless beans will hold only business logic, and no session [or user particular] data will be stored within. Hence injecting a stateful bean into stateless bean will give you inconsistent data. Even when your stateless bean is returned to the pool, it still holds onto the stateful bean, which might be returned again from the pool to service another client request, whose data might be well and truly different from the one being held in the stateful bean injected.
amol l a lekurwale
Joined: Oct 16, 2008
In that case, why it has been asked to use JNDI instead of DI? Is it because, we do JNDI lookup locally and so everytime the client stateless is used, it will do a fresh look up of the stateful bean?