Understanding JNDI
JNDI is like a map on steroids right? I use a key to find references to objects. Also, what is Initial开发者_StackOverflow中文版Context? I don't seem to get the idea.
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
精彩评论