What is the relationship between java:comp/env and

2019-01-30 16:06发布

问题:

What is the relationship between java:comp/env and java:global (regarding 3.1 spec)?
Seems like java:comp/env contains specific to EJB references. What means "specific" in this case?

回答1:

java:global is a namespace that's global for the entire application server, which includes other EAR modules (which are considered to be different applications).

java:comp/env is a much smaller namespace. For the web module, it corresponds to all web components (servlets etc) which are all together considered to be a single 'component' for JNDI, but for EJB beans it's a namespace for a single bean, since every bean is considered to be a separate component.

There's also a java:app and a java:module, whose scopes fall between global and comp.

A big difference between java:comp/env and the others is that the former is strictly read-only at runtime and contains among others the beans that are injected into some component. So e.g. consider:

@Stateless 
public class ExampleBean {

    @EJB
    OtherBean testBean;

}

In this case, the specific proxy that was injected into the field testBean can also be obtained from java:comp/env, but only when java:comp/env is referenced from within ExampleBean (JNDI is highly contextual).

If you however wanted a different proxy to the EJB OtherBean, or wanted a reference when no injection had been done, you can get those from any of the other scopes. Depending on from which class you're doing the JNDI call, you would be able to use smaller scopes.

For instance, if OtherBean is defined in the same module as ExampleBean, you could use java:module, if it's the same application (but possibly different modules) you can use java:app.

Finally, java:global is always safe to use, as it doesn't depend on the context. This means you could use from within e.g. a non-managed completely separate thread. The downside to using java:global is that you have to include the application name and the module name if an EAR is used, and otherwise at least the module name.