Sunday, May 19, 2013

JNDI Datasource in spring

There are two sources of database connections - either a  DataSource or a  DriverManager.

JNDI
The Java Naming and Directory Interface (JNDI) is part of the Java platform, providing applications based on Java technology with a unified interface to multiple naming and directory services. You can build powerful and portable directory-enabled applications using this industry standard.

Create JNDI Datasource while using Tomcat :- 
  1. Resource entry in server.xml under <GlobalNamingResources>
    You can find server.xml in following path in Tomcat folder :-
     c://Tomcat/conf/server.xml
  2. <globalnamingresources>
        <resource name="jdbc/test"  driverclassname="com.microsoft.sqlserver.jdbc.SQLServerDriver" maxwait="5000" password="makecodeeasy" type="javax.sql.DataSource" url="jdbc:sqlserver://localhost:1433;DatabaseName=DataTest" username="makecodeeasy" validationquery="select 1">
        </resource>
    </globalnamingresources>
    Note :- Database used here in MS Sql server 2008. You can use any database. You need to change driverClassname, url, username and password according to  database.
  3. Do the entry in web.xml
    You can find web.xml in WEB-INF folder of your application
  4. <resource-ref>
      <description>DB Connection Pooling</description> 
      <res-ref-name>java:comp/env/jdbc/test</res-ref-name> 
      <res-type>javax.sql.DataSource</res-type> 
      <res-auth>Container</res-auth> 
      <res-sharing-scope>Shareable</res-sharing-scope> 
    </resource-ref>
    
  5. Use datasource in applicationContext or spring context file
  6. <bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
      <property name="jndiName" value="java:comp/env/jdbc/test" /> 
      <property name="resourceRef" value="true" /> 
    </bean>
    
  7. Your Datasource is ready to use. It can also be used in hibernate.

4 comments:

ShareThis