JNDI explained

NOTE: The JNDI topic is to be expounded more, especially on how to create JNDI on Java code

JNDI or Java Naming Directory Interface lets you use a name that is tied up to a directory/URL. You may see some Web Server Application setup that you only need to put JNDI, then it can automatically connect like magic 🙂 . But underlying it is the real connection parameters with the real directory/URL location and all its credentials. JNDI name is like an “alias” access even if we switch to several directories/URLs and change credentials, JNDI name will remain the same and your application setup with the corresponding JNDI name wont be changed.

JNDI lookup name is just a one line of String.

Ex. “java:comp/env/jdbc/cebuCMSolutionsDb

How is JNDI used?

JNDI is clearly explained here as quote from stackoverflow.com:

— quote —

The most common use case is to set up a database connection pool on a Java EE application server. Any application that’s deployed on that server can gain access to the connections they need using the JNDI name “java:comp/env/FooBarPool” without having to know the details about the connection.

This has several advantages:

If you have a deployment sequence where apps move from devl->int->test->prod environments, you can use the same JNDI name in each environment and hide the actual database being used. Applications don’t have to change as they migrate between environments.
You can minimize the number of folks who need to know the credentials for accessing a production database. Only the Java EE app server needs to know if you use JNDI.

— quote —

What can JNDI do?

JNDI can let you access not just files and directories, but also URLs,  and other objects. It is used for Database connectivity, and other operating system services such DNS, LDAP and etc..

How is JNDI implemented?

We need to set Context.INITIAL_CONTEXT_FACTORY  in a HashMap or Properties object. Note that there are standard JNDI Factory classes for know Operating System services. here are the following:

Service Factory
Filesystem com.sun.jndi.fscontext.FSContextFactory or com.sun.jndi.fscontext.RefFSContextFactory
LDAPv3 com.sun.jndi.ldap.LdapCtxFactory
NDS com.novell.naming.service.nds.NdsInitialContextFactory
NIS com.sun.jndi.nis.NISCtxFactory
RMI registry com.sun.jndi.rmi.registry.RegistryContextFactory



Properties props = new Properties();

Reference URLs:

Database connectivity

JNDI explained in a nutshell


JNDI tutorials

JNDI tutorial with Security credentials