registered the JDBC driver [com.mysql.jdbc.Driver] but failed to unregister it when the web appli...

用idea开发一个springMVC+mybatis项目时,用到了数据源BasicDataSource,项目能正常运行,但在停止tomcat时,控制台出现警告: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.
在网上搜索了下解决方法,解决方法多数是针对在项目启动阶段报这个错,项目不能启动的场景,而且解决方法看起来要么觉得不适用要么觉得麻烦,连试下的心思都没有。偶然看到看到一篇文章介绍说是tomcat的版本问题,tomcat新检测机制导致的这个问题,换版本可以解决问题。
文章又说问题根源是BasicDataSource,BasicDataSource类close()的一个Bug。
BasicDataSource's method close() doesn't deregister JDBC driver. This causes permgen memory leaks in web server environments, during context reloads. For example, using Tomcat 6.0.26 with Spring, and BasicDataSource declared in Spring context, there is a message printed at web application reload:
SEVERE: A web application registered the JBDC 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.

而我用的是tomcat8.5.23,感觉换tomcat也不会解决问题,而且也不是解决问题的正途。用继承类,重写BasicDataSource的close方法倒是一个简单可行的办法。

解决方法:
继承org.apache.commons.dbcp.BasicDataSource 重写close()。

public class MyBasicDataSource extends BasicDataSource {
    @Override
    public synchronized void close() throws SQLException {
        DriverManager.deregisterDriver(DriverManager.getDriver(url));
        super.close();
    }
}

然后用 MyBasicDataSource 替换spring配置文件中的数据源bean的class,问题解决!

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容