Search code examples
javaspring-bootservletcontextlistener

How to register ServletContextListener in spring boot


Hello I'm trying to rewrite my old code to use Spring Boot. I have one listener public class ExecutorListener implements ServletContextListener.

How can I register this listener for Spring Boot? I've tried:

@SpringBootApplication
@ComponentScan
public class Application extends SpringBootServletInitializer {

    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
        super.onStartup(servletContext);
        servletContext.addListener(new ExecutorListener());
    }

}

But the contextInitialized method is not called.


Solution

  • You can try couple of things: Register ExecutorListener as a @Bean explicitly:

    @Bean
    public ExecutorListener executorListener() {
       return new ExecutorListener();
    }
    

    or

    You can try it with explicitly creating ServletRegistrationBean:

    @Bean
    public DispatcherServlet dispatcherServlet() {
        DispatcherServlet servlet=new DispatcherServlet();
        servlet.getServletContext().addListener(new ExecutorListener());
        return  servlet;
    }
    
    @Bean
    public ServletRegistrationBean dispatcherServletRegistration() {
        ServletRegistrationBean registrationBean = new ServletRegistrationBean(dispatcherServlet(), "/rest/v1/*");
        registrationBean
                .setName(DispatcherServletAutoConfiguration.DEFAULT_DISPATCHER_SERVLET_REGISTRATION_BEAN_NAME);
    
    
        return registrationBean;
    }