Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.

like image 366
Zac Tolley Avatar asked Feb 28 '14 17:02

Zac Tolley


People also ask

What is JNDI DataSource in tomcat?

Actual benefit of DataSource comes when we use it with a JNDI Context. For example, connection pool in a web application deployed in a servlet container. Most of the popular servlet containers provide built-in support for DataSource through Resource configuration and JNDI context.

Does tomcat use JNDI?

Tomcat provides a JNDI InitialContext implementation instance for each web application running under it, in a manner that is compatible with those provided by a Java Enterprise Edition application server. The Java EE standard provides a standard set of elements in the /WEB-INF/web.


2 Answers

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

like image 163
dustin.schultz Avatar answered Sep 23 '22 14:09

dustin.schultz


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

like image 43
nekperu15739 Avatar answered Sep 23 '22 14:09

nekperu15739