Why do they prefer bean JNDI search for EJB injection for a session?

I am new to Java EE and I cannot understand why I should prefer JNDI injection search over Stateful bean session? (This is what I read on a slide a lesson about it)

+4
source share
2 answers

In general, JNDI searches are performed when you are in a context that does not support injection.

If you are in a context that exists, there are several more reasons. One of them is that the bean that you enter will be serialized and does not know how to re-enter again after de-serialization (this happens for built-in JSF managed beans when using state on the client).

This last reason may be the reason the teacher had in mind. The beans session can be passivated (after which they will be serialized), and you may not want to serialize the embedded resource in some cases. In this case, you will not store the resource in the instance variable, but you will request a new one from JNDI every time you need it.

Another reason is that with JNDI you can programmatically decide which bean to get, but this does not apply to the beans state session and is performed for all types of injections anywhere.

Note that the above is mainly about entering an INTO session with a bean state. As Milleienus correctly states, there is also the question of introducing a session with a bean state into something. If you also do not assign an area for SFSB (via CDI @SessionScope, @RequestScope, etc.), then injecting into a servlet or other shared resource (for example, controlled by the bean application) will expose the same SFSB for all users which you most likely don’t want.

If you cannot use CDI (for example, maybe you just don’t know that it exists), then getting SFSB through JNDI is a workaround. If you want to keep the state longer than one method call, you will need to store it somewhere, for example, in an HTTP session.

+5
source

Suppose you are trying to get a link to an SFSB, for example. servlet. What are your options?

a) introducing EJB using the @EJB annotation

b) JNDI Search

Option a) provides you with the same link that will be used in all calls to a specific servlet. Perhaps, or definitely, not the behavior you want. Option b) is your choice, because you can get a new SFSB link for the request and save it only until you finish the call.

+3
source

Source: https://habr.com/ru/post/1445334/


All Articles