开发者

Proper way to call JNDI datasource within Tomcat

开发者 https://www.devze.com 2023-02-07 02:59 出处:网络
I am using a Java web application on a Tomcat server and would like to know what is the \"best practice\" in terms of accessing a database connection from within Tomcat\'s JNDI?开发者_高级运维

I am using a Java web application on a Tomcat server and would like to know what is the "best practice" in terms of accessing a database connection from within Tomcat's JNDI?

开发者_高级运维

Currently this is basically what I am doing each time I need to access the database:

Context envContext = null;
DataSource dataSource = null;
try {
    envContext  = (Context)ctx.lookup("java:/comp/env");
    dataSource = (DataSource)envContext.lookup("jdbc/datasource");
    return dataSource.getConnection();
} catch (Exception e){
    e.printStackTrace();
    return null;
}finally {
    if(envContext != null){
        try{
           envContext.close();
        } catch (NamingException e){
            e.printStackTrace();
        }
    }
}

However, is this the proper way to look up a connection from JNDI each time I want to access the database? Should I hold a reference to the Context or the Datasource instead?


new InitialContext() is expensive in every application container, it should be a static final and created in a static {} block, effectively making it a Singleton. You should only have to create this reference once and re-use it everywhere you need it.

DataSource should be a static as well. You should have a public static Connection getConnection(); method to retrieve Connection objects, the code should never have to deal with DataSource directly. This works especially well with PooledDataSource implementations.


The jndi lookups are essentially Map lookups so their overhead is minimal. But it is preferable to get the DataSource once and "cache" that. So if anything - writing a method to return the DataSource is ideal so as not to bind too much code to J2EE internals and make code easier to test.


You can do something like this too:-

...

Context initContext = new InitialContext();
DataSource dataSource = (DataSource) initContext.lookup("java:comp/env/jdbc/datasource");

...


Your lookup code looks ok
In your problem context, caching the datasource seems fine as long as you are not caching the actual connection object.

I haven't used this approach in a while though. These days, at a minimum, I use spring to inject the datasource/initialize JdbcTemplate

0

精彩评论

暂无评论...
验证码 换一张
取 消