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,问题解决!

你可能感兴趣的:(registered the JDBC driver [com.mysql.jdbc.Driver] but failed to unregister it when the web appli...)