0

I am trying to implement data pooling in a Tomcat7 container. My understanding is I have to use the following code to retrieve a data connection

        Context initContext;
        DataSource datasource = null;
        try {
            initContext = new InitialContext();
            Context envContext = (Context) initContext.lookup("java:/comp/env");
            datasource = (DataSource) envContext.lookup("jdbc/bolsms");
        } catch (NamingException ex) {
            Logger.getLogger(ReceiveC2DMRegistration.class.getName()).log(Level.SEVERE, null, ex);
        } 

My Question

For Context do I have to import javax.naming.context or org.apache.catalina.Context and for DataSource do I have to import javax.sql.DataSource or org.apache.tomcat.jdbc.pool.DataSource?

Gaurav Agarwal
  • 18,754
  • 29
  • 105
  • 166

1 Answers1

2

Declaring against Tomcat-specific classes/interfaces would make your webapp tight coupled to Tomcat and thus make it unable to run on other servers. You don't want to have that.

Always declare against standard Java SE/EE classes/interfaces wherever possible. This way your webapp will be portable across all server makes (Tomcat, Glassfish, JBoss AS, Jetty, etc).

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • Thanks. Just for knowledge. What is the difference? – Gaurav Agarwal Jul 17 '12 at 13:12
  • The one is a Tomcat-specific implementation and the other is a Java SE/EE standard interface/class. Declaring against vendor-specific implementation makes your code unportable. I'm not sure how that's hard to understand. Are you familiar with basic JDBC? It's an excellent example how and why interfaces should be used. See also for example this answer: http://stackoverflow.com/questions/7550612/in-simplest-terms-what-is-a-factory/7550752#7550752 – BalusC Jul 17 '12 at 13:15