To prevent a memory leak, the JDBC Driver has been forcibly unregistered

后端 未结 14 1470
执念已碎
执念已碎 2020-11-22 02:15

I am getting this message when I run my web application. It runs fine but I get this message during shutdown.

SEVERE: A web application registered the

14条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-22 03:19

    I see this issue come up a lot. Yes, Tomcat 7 does automatically deregister it, but it that REALLY taking control of your code and a good coding practice? Surely YOU want to know that you have all the correct code in place to close all your objects, shut down database connection pool threads, and get rid of all warnings. I certainly do.

    This is how I do it.

    Step 1: Register a Listener

    web.xml

    
        com.mysite.MySpecialListener
    
    

    Step 2: Implement the Listener

    com.mysite.MySpecialListener.java

    public class MySpecialListener implements ServletContextListener {
    
        @Override
        public void contextInitialized(ServletContextEvent sce) {
            // On Application Startup, please…
    
            // Usually I'll make a singleton in here, set up my pool, etc.
        }
    
        @Override
        public void contextDestroyed(ServletContextEvent sce) {
            // On Application Shutdown, please…
    
            // 1. Go fetch that DataSource
            Context initContext = new InitialContext();
            Context envContext  = (Context)initContext.lookup("java:/comp/env");
            DataSource datasource = (DataSource)envContext.lookup("jdbc/database");
    
            // 2. Deregister Driver
            try {
                java.sql.Driver mySqlDriver = DriverManager.getDriver("jdbc:mysql://localhost:3306/");
                DriverManager.deregisterDriver(mySqlDriver);
            } catch (SQLException ex) {
                logger.info("Could not deregister driver:".concat(ex.getMessage()));
            } 
    
            // 3. For added safety, remove the reference to dataSource for GC to enjoy.
            dataSource = null;
        }
    
    }
    

    Please feel free to comment and/or add...

提交回复
热议问题