JNDI is like a map on steroids right? I use a key to find references to objects. Also, what is InitialContext? I don't seem to get the idea.
Introduction. JNDI, part of the J2EE specification, provides naming and directory functionality for Java applications. Because JNDI is defined independently of any specific naming or directory service implementation, it enables Java applications to access different naming and directory services using a single API.
JNDI Description Any work with JNDI requires an understanding of the underlying service as well as an accessible implementation. For example, a database connection service calls for specific properties and exception handling. However, JNDI's abstraction decouples the connection configuration from the application.
JNDI is an API specified in Java technology that provides naming and directory functionality to applications written in the Java programming language. It is designed especially for the Java platform using Java's object model.
lookup() is used to find the specified object in the given context. i.e., it looks for a single, specific object and either find it in the current context or it fails.
Conceptually, JNDI is like System.getProperties()
on steroids.
System.getProperties()
allows you to pass String
parameters to your code from the command line. Similarly, JNDI allows you to configure arbitrary objects outside of your code (for example, in application server config files) and then use them in your code.
In other words, it's an implementation of Service Locator pattern: your code obtains services configured by environment from the centeral registry.
As usually with Service Locators, your code should have some entry point to access Service Locator. InitialContext
is this entry point: you create InitialContext
and then obtain required services from JNDI with lookup()
.
let's talk code, the class loading the jndi is a singleton, you will provide it the key to your jndi resources. Below, I'm loading a datasource (datasource="JDBC/dummy").
try { Context initCtx = new InitialContext(); Context envCtx = (Context) initCtx.lookup("jndicontext"); ds = (DataSource) envCtx.lookup("JDBC/dummy"); } catch (Exception e) { log.error(e); }
The initial context returns me the resource as an object. I could have loaded a bean the same way.
Connection conn = ds.getConnection();
But what is the point ? Just storing objects for specific environment without considering their type. And then changing their information on the fly. You will notice, I am not writing any login/password.
In this example, depending on the current environment : - In production, it returns a connection to a database. - In integration environment, it returns a connection to another database - In development, it instantiates another implementation of the class (mock ones) and uses xml files as datasource.
Regards
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With