For example, you can store configuration data such as IP addresses of application servers in a JNDI directory, and applications can access it.
JNDI can store and retrieve configuration information for an enterprise bean or any other application. It uses a client-side API to let applications perform directory operations such as binding or unbinding an enterprise bean to a JNDI directory. The directory is specified as a string name, called a naming context. The directory can be any naming service such as
A JNDI naming service provides the following benefits:
You can write programs using JNDI APIs without knowing how your application’s data is stored in a directory service.
You can write code to access data on a single machine or across multiple systems, as long as the resources are accessible from a JNDI directory.
You can write programs using JNDI in any programming language that provides a JNDI API.
Unfortunately, JNDI is not designed for high-performance environments and has some limitations:
Only certain types of data can be stored using the standard set method provided by JNDI, and data such as configuration information does not fit into this model.
There is no provision for transactions.
No built-in security model is provided, although some implementations provide APIs to set up SSL connections to directory servers.
Check out the examples below to understand the code better.
It is recommended to use DataSourceDefinition
annotations for configuring data sources as shown below.
@DataSourceDefinition
( name="java:jdbc/myDataSource"
jndi-name="java:global/jdbc/myDataSource",
driverClassName="com.mysql.jdbc.Driver",
url="jdbc:mysql://localhost:3306/mydatabase",
username="root",
password = "password")
public class myClass {
// ...
}
A name
uniquely identifies a resource to be looked up.
Below is the code example of a lookup for a JNDI resource using Resource
annotations.
@Resource(name="jdbc/MyDataSource")
private DataSource dataSource;
You can also use:
try {
InitialContext context = new InitialContext();
Object object = context.lookup("jdbc/MyDataSource"); // JNDI lookup
} catch (NamingException e) {
// code to handle the exception
}
Here, the context
is used to look up information about the naming environment where all named resources are registered. The lookup method will return a data source object, which you could do as shown below.
object.getConnection()