How do I load a java class (not a servlet) when the tomcat server starts [duplicate]

Let that class implement ServletContextListener. Then you can do your thing in contextInitialized() method.

public class Config implements ServletContextListener {

    public void contextInitialized(ServletContextEvent event) {
        // Webapp startup.
    }

    public void contextDestroyed(ServletContextEvent event) {
        // Webapp shutdown.
    }

}

Register it in web.xml as follows to get it to run:

<listener>
    <listener-class>com.example.Config</listener-class>
</listener>

Or if you’re already on Servlet 3.0, then just use @WebListener annotation on the class.

Leave a Comment