JNDI

Java Naming and Directory Interface (JNDI) provides naming and directory functionality to applications written in the Java programming language. It is designed to be independent of any specific naming or directory service implementation. Thus a variety of services-new, emerging, and already deployed ones, can be accessed in a common way.

The JNDI architecture consists of an API (Application Programming Interface) and an SPI (Service Provider Interface). Java applications use this API to access a variety of naming and directory services. The SPI enables a variety of naming and directory services to be plugged in transparently, allowing the Java application using the API of the JNDI technology to access their services.

The tomcat conf/context.xml configuration,

<Resource 
    factory="org.apache.tomcat.jdbc.pool.DataSourceFactory"
    type="javax.sql.DataSource"
    maxactive="50"
    minIdle="5"
    maxidle="10"
    maxWait="90000"
    testOnBorrow="true"
    validationQuery="select 1"
    driverClassName="DB-DRIVER-CLASS"
    url="DB-CONNECTION-URL"
    name="JNDI-NAME"
    username="USER_NAME"
    password="PASSWORD" />

The InitialContext is configured as a web application is initially deployed, and is made available to web application components (for read-only access). All configured entries and resources are placed in the java:comp/env portion of the JNDI namespace, so a typical access to a resource - in this case, to a JDBC DataSource is below,

// Obtain our environment naming context
Context initialContext = new InitialContext();
Context envContext = (Context) initialContext.lookup("java:comp/env");

// Look up our data source
DataSource dataSource = (DataSource) envContext.lookup("JNDI-NAME");

// Allocate and use a connection from the pool
try (Connection connection = dataSource.getConnection()) {
    // Execute DB DDL/DML queries using connection object
}
// close resources (Context, DataSource)