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.
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
Conceptually, JNDI is like
System.getProperties()
on steroids.System.getProperties()
allows you to passString
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 createInitialContext
and then obtain required services from JNDI withlookup()
.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").
The initial context returns me the resource as an object. I could have loaded a bean the same way.
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