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.

其他提示

Let's assume that you're trying to obtain a reference on SFSB in e.g. servlet. What are your options?

a) injecting EJB with @EJB annotation

b) JNDI lookup

Option a) would give you same reference that would be shared across all invocations of specific servlet. Probably, or definitely, not the behaviour you want. Option b) is your choice, because you can obtain new SFSB reference per-request, and keep it only until you're finished with invocation.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top