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:

<GlobalNamingResources>
..............
     <Resource
      name="jdbc/testDatasource"
      type="javax.sql.DataSource"
      maxActive="4"
      maxIdle="2"
      username="yourDbUser"
      maxWait="5000"
      validationQuery="select 1"
      driverClassName="com.mysql.jdbc.Driver"
      password="yourpPassword"
      url="jdbc:mysql://yourDatabase.com/yourDBname"/>
   </GlobalNamingResources>

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

<resource-ref>
        <description>My Datasource</description>
        <res-ref-name>jdbc/testDatasource</res-ref-name>
        <res-type>javax.sql.DataSource</res-type>
        <res-auth>Container</res-auth>
    </resource-ref>

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 jndi.properties 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 jndi.properties 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 Tomcat.java unit testing framework

    ReplyDelete