Why use JNDI for data sources

JNDI really shines when you have to move an application between environments: development to integration to test to production. If you configure each app server to use the same JNDI name, you can have different databases in each environment and not have to change your code. You just pick up the WAR file and drop it in the new environment.

Here are some other assumptions that are crucial to know when judging this answer:

  • I don't have access to the servers on which the code is deployed at all, except for read-only access to logs.
  • The person who writes and packages the code is not the same person who configures and manages the server.
  • Once a WAR file starts on its journey to PROD it cannot be changed again without going back to the beginning. Any testing that's done by QA on the test server must be re-done if the WAR is altered.

Perhaps you don't see this benefit because you're a lone developer who writes code on a local desktop and deploys right to production.


I think the "preferred" mechanism is the one that's preferred by the person doing the admin and configuration. As duffymo pointed out, it's crucial that the configuration be external to your deployable artifact, but otherwise, I'd say anything goes. If your sysadmin prefers using a GUI to configure JDNI entries, cool. If he/she prefers editing properties files with cssh and vi, cool too. If you're responsible for both developing and configuring/deploying your app, then that's pretty much your call. Personally, I like to keep as much implementation as possible inside my artifact, meaning that my data source and drivers live there, too.

If you're asking about technical benefits of JNDI over the alternatives, I'm not sure there are any, but you might want to clarify your question.


As mentioned by others JNDI for the most part is used for service location lookup but mainly for DB like resources.

Whats most annoying is that Java's LDAP API is also the JNDI API. When working with LDAP the abstractions are very very confusing. JNDI also has the disadvantage of sometimes being a single point of failure.

You can easily accomplish most of what JNDI does by using Host name aliases. That is make an alias that points MYRESOURCE to 127.0.0.1 in your /etc/hosts (or wherever it is for your env). Then in your App config use MYRESOURCE as the host name (in a jdbc url for example).

Then when you move your app to production just change the production's /etc/hosts file to point MYRESOURCE to the production resource/service (like prod database server).

The above is a way more portable smaller footprint naming directory that will work in other languages (ruby, python). It will also work with things that are not normally done with JNDI like REST services. The only annoying thing is that you will have to update your servers hosts files but this can be automated through SSH scripts.