Skip to content

spring jndi

Eric F. Alsheimer edited this page Jan 24, 2018 · 6 revisions

Spring JNDI

JNDI is Java Naming and Directory Interface. A naming service or directory service is a map of network resources to network addresses.

JNDI is used to abstract the connection information away from data sources, so in practice your code is portable between servers and data sources. With JNDI, you configure the data source into the Tomcat instance, then the application connects to the Tomcat instance and requests connection information (as a value) from a particular name (as a key).

Add JNDI to a Tomcat Instance

You need to make a <Resource ... /> tag in the context.xml file for your Tomcat instance. You can find online some normal properties like u/p, name, url, etc.

<Resource name="jdbc/springdb" 
  auth="Container" 
  type="javax.sql.DataSource"
  maxActive="100" 
  maxIdle="30" 
  maxWait="10000"
  username="devuser"
  password="lab49" 
  driverClassName="com.mysql.cj.jdbc.Driver"
  url="jdbc:mysql://localhost:3306/spring_db"/>

Note: Sometimes you will lose your server. It seems to be a problem with Eclipse when Tomcat is installed separately. Normally you can just make a new server and put the JNDI configuration in the context.xml file of the new server. Every once in a while, however, it's better to delete all existing servers (on the drive, not just in Eclipse) and then spin up a completely new server with a changed config.xml

You also have to wire up a data source in your Spring Web Configuration (WebMvcConfig.java):

@Bean
public DataSource dataSource() {
  final JndiDataSourceLookup dsLookup = new JndiDataSourceLookup();
  dsLookup.setResourceRef(true);
  DataSource dataSource = dsLookup.getDataSource("jdbc/springdb");
  return dataSource;
}

You'll use the name of the resource tag as the name of the data source.

Clone this wiki locally