用idea開發(fā)一個springMVC+mybatis項目時,用到了數(shù)據(jù)源BasicDataSource进胯,項目能正常運行,但在停止tomcat時,控制臺出現(xiàn)警告: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.
在網(wǎng)上搜索了下解決方法逆皮,解決方法多數(shù)是針對在項目啟動階段報這個錯,項目不能啟動的場景参袱,而且解決方法看起來要么覺得不適用要么覺得麻煩电谣,連試下的心思都沒有。偶然看到看到一篇文章介紹說是tomcat的版本問題抹蚀,tomcat新檢測機制導(dǎo)致的這個問題剿牺,換版本可以解決問題。
文章又說問題根源是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也不會解決問題郑现,而且也不是解決問題的正途湃崩。用繼承類,重寫B(tài)asicDataSource的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配置文件中的數(shù)據(jù)源bean的class,問題解決辛友!