How to register ServletContextListener in spring boot
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;
}
In case you prefer auto discovery using annotations only, make your ExecutorListener
implement the ServletContextInitializer
and e.g. annotate it with javax.annotation.ManagedBean
. From there, just implement the onStartup
method:
@ManagedBean
public final class ExecutorListener implements ServletContextInitializer {
...
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
...
}
}
If using an embedded container, there will soon be a third option if using SpringBoot 1.3.0+
Annotate your ServletContextListener
implementation with @WebListener
from servlet spec 3, then annotate one of your Spring @Configuration
classes with the new @ServletComponentScan
(and optionally tell it which packages to scan for filters, servlets and listeners).
Only available in 1.3.0+ at the moment though: http://docs.spring.io/spring-boot/docs/current/api/org/springframework/boot/web/servlet/ServletComponentScan.html
Docs: http://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#boot-features-embedded-container-servlets-filters-listeners