Srini M
Srini M

Reputation: 308

Tomcat JDBC datasource lookup failing in Spring app

JDBC JNDI lookup started failing on my application after making it Spring aware.

  1. JDBC datasource setup on tomcat is correct as the non-spring application is able to connect with same setup.
  2. Attempted to initiatize JNDIFactoryBean in Application's spring config.
    <beans>
    <bean id="myDb" class="org.springframework.jndi.JndiObjectFactoryBean">
      <property name="jndiName" value="java:comp/env/jdbc/myDb"/>
      <property name="lookupOnStartup" value="true"/>
      <property name="proxyInterface" value="javax.sql.DataSource"/>
    </bean>
    </beans>
  1. Also attempted adding resource-ref in web.xml of the application.
 <resource-ref> 
  <res-ref-name>jdbc/myDb</res-ref-name>
  <res-type>javax.sql.DataSource</res-type>
   <res-auth>Container</res-auth> 
   <res-sharing-scope>Shareable</res-sharing-scope> 
  </resource-ref> 
 </web-app>
  1. Since publishing this thread, also tried 'jee:jndi-lookup' in spring config.xml.
<jee:jndi-lookup expected-type="javax.sql.DataSource" id="myDb" jndi-name="java:comp/env/jdbc/myDb"/>

JDBC JNDI Datasource Setup

CATALINA_HOME/conf/server.xml

<GlobalNamingResources>
    ......

    <Resource auth="Container" driverClassName="com.microsoft.sqlserver.jdbc.SQLServerDriver" maxIdle="5" maxTotal="25" name="jdbc/myDb" password="ABDC" type="javax.sql.DataSource" url="jdbc:sqlserver://myServer:1233;databaseName=myDBdbdev" username="myUser"/>
  </GlobalNamingResources>

CATALINA_HOME/conf/context.xml

<context>
    <ResourceLink global="jdbc/myDb" name="jdbc/myDb" type="javax.sql.DataSource"/>
    ...

</context>

Error StackTrace

javax.naming.NameNotFoundException: Name [jdbc/myDb] is not bound in this Context. Unable to find [jdbc]. at org.apache.naming.NamingContext.lookup(NamingContext.java:833) at org.apache.naming.NamingContext.lookup(NamingContext.java:174) at org.apache.naming.SelectorContext.lookup(SelectorContext.java:163) at javax.naming.InitialContext.lookup(Unknown Source) at com.abc.myapp.db.DataSourceFactory.createPool(DataSourceFactory.java:126) at com.abc.myapp.db.DataSourceFactory.init(DataSourceFactory.jav

Code for fetching datasource

InitialContext ctx = new InitialContext();
ds = (DataSource)ctx.lookup("jdbc/myDb");

Upvotes: 0

Views: 1832

Answers (1)

Srini M
Srini M

Reputation: 308

What I just found was the below code helps fetch the datasource correctly:

InitialContext ctx = new InitialContext();
ds = (DataSource)ctx.lookup("java:comp/env/jdbc/myDb")

Upvotes: 1

Related Questions