How do you use a Tomcat JNDI JDBC datasource in Spring Boot

Here's what I had done.

Add the following to to Application.java

@Bean
public DataSource dataSource() {
  JndiDataSourceLookup dataSourceLookup = new JndiDataSourceLookup();
  DataSource dataSource = dataSourceLookup.getDataSource("java:comp/env/jdbc/mysqldb");
  return dataSource;
}

Then follow the example in https://spring.io/guides/gs/accessing-data-jpa/ to set up the TransactionManager and Hibernate specific properties.


If you're using Spring Boot 1.2 or greater, this got easier. You can just add this to application.properties

spring.datasource.jndi-name=java:comp/env/jdbc/my_database

The relevant docs: http://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-sql.html#boot-features-connecting-to-a-jndi-datasource


@Bean
public DataSource dataSource() {
  JndiDataSourceLookup dataSourceLookup = new JndiDataSourceLookup();
  DataSource dataSource = dataSourceLookup.getDataSource("jdbc/apolloJNDI");
  return dataSource;
}

No "java:comp/env/" its needed because JndiDataSourceLookup internaly calls convertJndiName that add this part. In other clases you should set the complete path.