Search code examples
vaadinvaadin8

Run code in Vaadin 8 application idependent of UI


In earlier versions, you could have a class which implements ServletContextListener and put your code in the contextInitialized method, so that it runs when the server starts. This is useful for loading up the database into memory. How does one achieve this in a Vaadin 8 project?


Solution

  • In exactly the same way: By registering a ServletContextListener. You can use the @WebListener annotation for this. For example:

    public class WebConfig {
    
        @WebServlet("/*")
        @VaadinServletConfiguration(ui = VaadinUI.class, productionMode = false)
        public static class JdbcExampleVaadinServlet extends VaadinServlet {
        }
    
        @WebListener
        public static class JdbcExampleContextListener implements ServletContextListener {
    
            @Override
            public void contextInitialized(ServletContextEvent sce) {
                try {
                    DatabaseService.init();
    
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
    
            @Override
            public void contextDestroyed(ServletContextEvent sce) {
                DatabaseService.shutdown();
            }
        }
    
    }