更新:显然,Tomcat 从 7.0.11 开始,为您关闭了数据源,因此它在 web 应用程序的 contextDestroyed 中不可用。看:https://issues.apache.org/bugzilla/show_bug.cgi?id=25060
Hi,
我正在使用 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 侦听器中的数据源?
Thanks,
Paul
我不同意。我将向您的 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);
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)