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.
Just add a @Bean method which constructs the RequestContextListener . Spring Boot will do the rest.
ServletContextEvent class provides alerts/notifications for changes to a web application's servlet context. ServletContextListener is a class that receives alerts/notifications about changes to the servlet context and acts on them.
void contextInitialized(ServletContextEvent sce) Receives notification that the web application initialization process is starting. All ServletContextListeners are notified of context initialization before any filters or servlets in the web application are initialized.
ServletContextListener receives the notifications about changes to the servlet context and perform some action. ServletContextListener is used to perform important task at the time when context is initialized and destroyed.
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; }
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With