Thursday, March 3, 2011

Spring JNDI configuration with Tomcat

I was really curious about how to configure data source  using Spring JNDI lookup and Tomcat.

I am using Spring 3.0.5, Tomcat 6.0.14 and MySql. Here is what I did:

1) In my Spring config xml file, application-config.xml , I used Spring JNDI lookup tag to create dataSource bean

<jee:jndi-lookup id="myDataSource" jndi-name="jdbc/testDatasource"/>

2) In Tomcat's server.xml I  added <resource> tag to <GlobalNamingResources> tag:

      validationQuery="select 1"

3) In tomcat's LIB folder I added mysql-connector-java-5.1.14.jar (you add an appropriate JDBC driver jar)

4) Now, I was trying to start up my Tomcat from Eclipse and it didn't work at first. I added this code to my web.xml

        <description>My Datasource</description>

and I was able to start the Server from Eclipse Server configuration.

To run JUnit tests, I don't think there is a way to use JNDI if you don't run them from the Tomcat's container. Although I wish thare is a way to do it. I tried to run JUnit tests with my configuration in Eclipse. As far as I got is that I had to have file in my classpath.  Without it I get the following Exception:

javax.naming.NoInitialContextException: Need to specify class name in environment or system property, or as an applet parameter, or in an application resource file:  java.naming.factory.initial

When I added and I also created jndi.xml, I got  this Error:

Error creating bean with name 'dataSource': Invocation of init method failed; nested exception is java.lang.StackOverflowError

1 comment:

  1. I was really curious about how to configure data source using Spring JNDI lookup and unit testing framework