November 01, 2013

Quick GlassFish JNDI Custom Resources

Overview

This is a quick overview of using GlassFish JNDI Custom Resources. These are a great way to be able to provide dynamic configuration of your application at run time. When JNDI values are changed, the new values get to all cluster instances and if your code is written to lookup the values then the new values will be found the next time your code is executed by the server.

Creating a GlassFish JNDI Custom Resource

This is very easy.  The screenshot below shows how to do this with the GlassFish administration console. 
The only little trick with creating resources of java.lang.String is then name of the property must be "value".
The example shown below creates a JNDI string property bound to contactUs/emailToAddress.  The purpose of this property is to define what email address should be emailed when a user of your website fills out your company's "contact us" page.  



Getting a Glassfish JNDI Custom Resource Value

Getting a JNDI Custom Resource value from your code is very easy.  The code snippet below shows how.  By manually performing the lookup, you can ensure the code will get the latest and great value out of JNDI every time.  When using @Inject or @Resource that may not happen.
 
String emailToAddress = "";
try {
  InitialContext ic = new InitialContext();
  emailToAddress = (String) ic.lookup("contactUs/emailToAddress");
} catch (NamingException e) {
  throw new RuntimeException(e);
}

That's it. Real simple and easy.