Showing posts with label JNDI. Show all posts
Showing posts with label JNDI. Show all posts

Friday, 17 January 2020

SpringBoot Configure DataSource Using JNDI with Example using Tomcat 9 Server

🚀 Master Advanced Spring Boot!

Join Ram N Java for professional tutorials on server configuration and Java development!

SUBSCRIBE TO THE CHANNEL

Spring Boot JNDI DataSource Configuration

In enterprise environments, managing database connections through JNDI (Java Naming and Directory Interface) is a standard practice. It allows the server to manage the connection pool, making your application more portable and secure. This guide reveals the "secrets" of setting up a JNDI DataSource in Spring Boot when deploying to Tomcat 9.

Step 1: Configure Tomcat's context.xml

The first step happens outside your application. You need to define the Resource in Tomcat's context.xml file. Here, you specify the driver class, database URL, username, password, and pooling parameters. This makes the DataSource available to any application running on the server.

Step 2: Update application.properties

Spring Boot needs to know where to look for the JNDI resource. Instead of providing database credentials in your properties file, you simply provide the JNDI name using spring.datasource.jndi-name. This keeps your application configuration clean and environment-independent.

Step 3: Creating the DataSource Bean

In your Spring configuration class, you can programmatically define the DataSource bean. By using JndiDataSourceLookup, Spring can fetch the pre-configured DataSource from the Tomcat container seamlessly during the application startup process.

Step 4: Handling the "java:comp/env" Prefix

One common pitfall is the JNDI prefix. Depending on your configuration, you might need to prepend java:comp/env/ to your resource name. Understanding how Tomcat namespaces these resources is key to a successful connection.

Step 5: Verify the Connection

Run your application on the external Tomcat server. If configured correctly, Spring Boot will successfully acquire the connection from the server's pool. You can verify this by checking your logs for the successful initialization of the Hikari or Tomcat connection pool.

Tutorials