Search code examples
javaspringjndi

JNDI lookup of PostgreSQL database in tomcat


In existing application I am connecting to database using jndi as follows. Please guide me on how I can write effective code for same in Spring based application.

My Current jndi lookup code is

InitialContext context = null;
String welcomeMessage = null;
Integer maxSessionCount = null;

try{
    context = new InitialContext();

    welcomeMessage = (String)context.lookup(
            "java:comp/env/welcomeMessage");
    maxSessionCount = (Integer)context.lookup(
            "java:comp/env/maxSessionCount");
}
catch (NamingException exception){
    exception.printStackTrace();
}

Solution

  • <jee:jndi-lookup id="dbDataSource"
       jndi-name="jdbc/DatabaseName"
       expected-type="javax.sql.DataSource" />
    

    Declare the JNDI resource in tomcat's server.xml using something like this:

    <GlobalNamingResources>
      <Resource name="jdbc/DatabaseName" auth="Container" type="javax.sql.DataSource"
                  username="dbUsername" password="dbPasswd"
                  url="jdbc:postgresql://localhost/dbname"
                  driverClassName="org.postgresql.Driver"
                  initialSize="5" maxWait="5000"
                  maxActive="120" maxIdle="5"
                  validationQuery="select 1"
                  poolPreparedStatements="true"/>
    </GlobalNamingResources/>
    

    And reference the JNDI resource from Tomcat's web context.xml like this:

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

    make use of bean dbDatasource in your application.