Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why prefer JNDI lookup over EJB injection for a Stateful session bean?

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)

like image 692
Matthieu Riegler Avatar asked Feb 19 '23 13:02

Matthieu Riegler


1 Answers

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.

like image 61
Arjan Tijms Avatar answered Feb 21 '23 03:02

Arjan Tijms