Search This Blog

Thursday, November 15, 2018

Java EE Portable JNDI Examples

The general syntax of a portable global JNDI name of an EJB is of the form:

java:global/[<application-name>]/<module-name>/<bean-name>!<fully-qualified-bean-interface-name>

new InitialContext().lookup("java:global/ProjectName/ModuleName/BeanName!FullyQualif‌​iedNameOfRemoteInterface");


Every Java EE container must assign (at least one) well defined global JNDI names to EJBs. In addition to the above name, if the EJB exposes just a single client view (that is it implements just one interface or the no interface view), the container is also mandated to map the bean to

java:global/[<application-name>]/<module-name>/<bean-name>

In addition to the java:global namespace, the container is also required to make the bean(s) available under two other name spaces:
java:app and java:module. The java:app and java:module names are of the form:

java:app/<module-name>/<bean-name>!<fully-qualified-intf-name>

and

java:module/<bean-name>!<fully-qualified-intf-name>

Most of the time the beans and the clients are collocated in the same application or even within the same module, java:module allows a component executing within a Java EE application to access a namespace rooted below the <module-name> portion of the namespace corresponding to its module. 

java:module can be treated as the jndi sub-context that is rooted under the "current module" in which the client is located. java:module differs from java:global in the sense that the client can access only those beans that are packaged inside the same module as the client. If a component in moduleA has to look up a component in moduleB, then it has to use java:global (or java:app).

Similarly, java:app can be treated as the jndi sub-context that is rooted under the "current app" in which the client is located.

You can also use the portable jndi names in injection too

@EJB(lookupName="java:global/hello/I88Ca")
private I88Ca i88Ca;

To list all the JNDI entries:

InitialContext ctx = new InitialContext();
NamingEnumeration<NameClassPair> list = ctx.list("");
while (list.hasMore()) {
  System.out.println(list.next().getName());
}