更新:显然,从7.0.11开始,Tomcat已为您关闭了数据源,因此在Webapp的contextDestroyed中不可用。参见:https://issues.apache.org/bugzilla/show_bug.cgi?id=25060

你好

我正在使用Spring 3.0和Java 1.6。

如果以这种方式获取数据源:

<bean id="dataSource" class="my.data.Source" destroy-method="close">
    <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"/>
    <property name="url" value="jdbc:oracle:thin:@localhost:1521:home"/>
    <property name="username" value="user"/>
    <property name="password" value="pw"/>
</bean>


然后在销毁bean时关闭数据源。

如果我得到这样的数据源:

<jee:jndi-lookup id="dataSource" jndi-name="java:comp/env/jdbc/db" />


那么我是否必须在我的contextDestroyed侦听器中显式关闭数据源?

谢谢,

保罗

最佳答案

我不同意。我将在您的web.xml中添加一个侦听器并实现contextDestroyed()方法。当Web应用程序被销毁或取消部署时,Web容器/应用程序服务器将调用此方法。在contextDestroyed()中,我将关闭数据源。

在web.xml中

<listener>
   <listener-class>util.myApplicationWatcher</listener-class>
</listener>


代码:

package util;

public class myApplicationWatcher implementes ServletContextListener
{
  public void contextInitialized(ServletContextEvent cs)
  {
      // This web application is getting started

      // Initialize connection pool here by running a query
      JdbcTemplate jt = new JdbcTemplate(Dao.getDataSource() );
      jt.queryForInt("Select count(col1) from some_table");
  }

  public void contextDestroyed(ServeletContextEvent ce)
  {
      // This web application is getting undeployed or destroyed

      // close the connection pool
      Dao.closeDataSource();
  }
}

public class Dao
{
  private static DataSource ds;
  private static bDataSourceInitialized=false;
  private static void initializeDataSource() throws Exception
  {
    InitialContext initial = new InitialContext();

    ds = (DataSource) initial.lookup(TOMCAT_JNDI_NAME);

    if (ds.getConnection() == null)
    {
      throw new RuntimeException("I failed to find the TOMCAT_JNDI_NAME");
    }

    bDataSourceInitialized=true;
  }

  public static void closeDataSource() throws Exception
  {
    // Cast my DataSource class to a c3po connection pool class
    // since c3po is what I use in my context.xml
    ComboPooledDataSource cs = (ComboPooledDatasource) ds;

    // close this connection pool
    cs.close();
  }

  public static DataSource getDataSource() throws Exception
  {
    if (bDataSourceInitialized==false)
    {
      initializeDataSource();
    }

    return(ds);
  }
}

09-16 06:49