Question

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.

Was it helpful?

Solution 2

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

OTHER TIPS

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

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.

A hint for all of you using Spring Boot with an external Tomcat. Please ensure your war doesn't contain any tomcat jars. Multiple versions of same jar will produce hidden ClassCastException manifested by javax.naming.NamingException.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top