The web application registered the JDBC driver * but failed to unregister it when the web application was stopped. To prevent a memory leak, the JDBC Driver has been forcibly unregistered.

最近使用了最新版的tomcat9,使用jdbc链接mysql数据库。关闭tomcat过程中出现警告

13-Sep-2017 22:22:54.369 WARNING [main] org.apache.catalina.loader.WebappClassLoaderBase.clearReferencesJdbc The web application [license] registered the JDBC driver [com.mysql.jdbc.Driver] but failed to unregister it when the web application was stopped. To prevent a memory leak, the JDBC Driver has been forcibly unregistered.

时间有限没有去追源码,网上的说法:

tomcat6最新版本引入内存溢出检测阻止机制,检测到jdbc在tomcat运行时进行注册,但是当tomcat停止时没有解除注册。

原因是在tomcat停止之前没注销驱动。

网上有的方式是重写org.apache.commons.dbcp.BasicDataSource,这个不推荐。既然是容器级别的事件,那就从事件入手。

@WebListener
public class AppContextListener implements ServletContextListener{ public void contextDestroyed(ServletContextEvent event) {
try{
while(DriverManager.getDrivers().hasMoreElements()){
DriverManager.deregisterDriver(DriverManager.getDrivers().nextElement());
}
}catch(Exception e){
e.printStackTrace();
}
} public void contextInitialized(ServletContextEvent event) {
ServletContext context = event.getServletContext();
String rootPath = context.getRealPath("/");
System.setProperty("rootPath", rootPath); //logger.info("global setting,rootPath:{}",rootPath);
//logger.info("deployed on architecture:{},operation System:{},version:{}",
// System.getProperty("os.arch"), System.getProperty("os.name"),
// System.getProperty("os.version"));
//logger.info("app startup completed....");
}
}

Tomcat在停止web应用的时候会调用contextDestroyed方法,加入你的项目,即可在tomcat关闭时注销已经注册的JDBC驱动。

以上代码适用于servlet3.0 web容器,servlet 2.5容器需要在web.xml添加配置文件。

servlet容器2.5用法

public class AppContextListener implements ServletContextListener{

    public void contextDestroyed(ServletContextEvent event)  {
try{
while(DriverManager.getDrivers().hasMoreElements()){
DriverManager.deregisterDriver(DriverManager.getDrivers().nextElement());
}
}catch(Exception e){
e.printStackTrace();
}
} public void contextInitialized(ServletContextEvent event) {
ServletContext context = event.getServletContext();
String rootPath = context.getRealPath("/");
System.setProperty("rootPath", rootPath); //logger.info("global setting,rootPath:{}",rootPath);
//logger.info("deployed on architecture:{},operation System:{},version:{}",
// System.getProperty("os.arch"), System.getProperty("os.name"),
// System.getProperty("os.version"));
//logger.info("app startup completed....");
}
}

web.xml

<web-app>
<listener>
<listener-class>com.xxxx.init.AppContextListener</listener-class>
</listener>
</web-app>

至此,问题解决。

上一篇:Java基本语法(一)


下一篇:解决:The web application [] registered the JDBC driver [] but failed to unregister it when the web application was stopped. To prevent a memory leak, the JDBC Driver has been forcibly unregistered.