When I try to use a JNDI datasource with Spring Boot and Spring Data JPA using an embedded Tomcat server, I get the following error message when running the application with SpringApplication.run:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.class]: Instantiation of bean failed;
nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean org.springframework.boot.autoconfigure.orm.jpa.JpaBaseConfiguration.entityManagerFactory(org.springframework.boot.autoconfigure.orm.jpa.EntityManagerFactoryBuilder)] threw exception;
nested exception is org.springframework.jndi.JndiLookupFailureException: JndiObjectTargetSource failed to obtain new target object;
nested exception is javax.naming.NameNotFoundException: Name [comp/env/jdbc/myDataSource] is not bound in this Context. Unable to find [comp].
I use the configuration described in the solution of How to create JNDI context in Spring Boot with Embedded Tomcat Container
The only difference is the additional Maven dependency to org.springframework.boot:spring-boot-starter-data-jpa
Here is a sample project: https://github.com/derkoe/spring-boot-sample-tomcat-jndi (this is a modified version of the sample in the solution). Just check out, build and run SampleTomcatJndiApplication.
It seems that the JNDI context used in looking up the database connection is not yet the one from the webapp. This seems to be an ordering problem in the initialization of the Spring context and the Tomcat server.
Any ideas how to solve that?