I'm quite new to Java EE and I can't figure out why I should prefer JNDI lookup over injection for a Stateful session bean ? (That's what I read on slide of a lesson about it)
In general JNDI lookups are being done when you're in a context that doesn't support injection.
If you are in a context that does, there are several reasons still. One is when the bean you are injecting in is going to be serialized, and doesn't know how to re-inject again after de-serialization (this happens for JSF native managed beans when using state on client).
This last reason may possibly be the reason the teacher had in mind. Stateful session beans can be passivated (after which they will be serialized), and perhaps in some circumstances you wouldn't want the injected resource to be serialized as well. In that case you wouldn't store the resource in an instance variable, but would request a new one from JNDI every time you need one.
Another reason is that with JNDI you can programmatically make a decision regarding which bean to retrieve, but this is not specific for stateful session beans and holds for all types of injections anywhere.
Note that the above is mainly about injecting INTO a stateful session bean. As Miljen above correctly states, there's also the question of injecting a stateful session bean into something. If you don't also assign a scope to the SFSB (via CDI's @SessionScope, @RequestScope, etc), then injecting into a Servlet or other shared resource (like an Application scoped managed bean) will expose the same SFSB to all users, which is something you most likely do not want.
If you can't use CDI (e.g. perhaps you just don't know it exists), then obtaining the SFSB via JNDI is a workaround. If you want to keep the state around for longer than a single method call, then you would have to store it somewhere though, e.g. in the HTTP session.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With