Search code examples
tomcat7spring-data-jpaspring-boot

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


I have a Spring boot application and want to deploy as a WAR to Tomcat 7. As part of this I need to keep configuration out of the WAR, so that I can deploy the same war to my stage and production servers and have it pickup the mysql connection via configuration.

To this end I want to configure my Spring Boot app to use a mysql connection configured as a JNDI datasource in the Tomcat instance.

Can spring boot do this and if so how?

Alternatively is this easy to do in Spring 4 without resorting to xml based configuration.


Solution

  • @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.